PHP Check complicated String for correct format

纵饮孤独 提交于 2019-12-13 09:22:30

问题


Looking for some help on how to validate a string in PHP.

The format to validate against is

X.XXam[d[i]-d[i] Only]

A sample entry could be:

8:55pm[Tues-Thurs Only]

d[i] represents an associative array value depending on the day of the week. For instance, the above contains Saturday and Sunday.

I need to make sure/validate this before inserting in the DB.

Can I get some help with this?


回答1:


Check out regex 101. It is a wonderfull Tool to create regular expressions and understand them. From there i got this solution for you:

%^\d{1,2}:\d{1,2}([ap])m\[(Mon|Tue|Wed|Thu|Fri|-){1,} Only\]$%mg

The first bit (\d{1,2}) accepts a number between 0 and 99, then a : and another number between 0 and 99. Then it is either a or p followed by m. Then you have either Mon or Tue or .... or - for 1 to endles times.

At the end you have the modifiers g and m. The m is to make use of the ^ and $ modifiers that represent the beginning and the end of a line. The g is just to find ALL results rather than the first existing. You can leave that out.

To use Weekdays from an array called $array simply implode it to a string and fill it into your expression like this:

$weekdaysString = implode('|',$array);
$regex = '%^\d{1,2}:\d{1,2}([ap])m\[('.$weekdaysString.'|-){1,} Only\]$%mg';

Read up on implode.




回答2:


this should work for your case :

^\d{1,2}:\d{2}[ap]m\[\w+\-\w+ Only]$

demo here : http://regex101.com/r/mH9lX1



来源:https://stackoverflow.com/questions/23221936/php-check-complicated-string-for-correct-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!