且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP检查复杂的字符串是否格式正确

更新时间:2023-02-23 09:25:03

检查正则表达式101.这是一个奇迹创建正则表达式并理解它们的工具。从那里我得到了这个解决方案

 %^ \d {1,2}:\d {1,2}([AP])m\ [(周一|星期二|星期三|星期四|星期五|  - ){1,}只有...] $%mg 

第一位( \d {1,2} )接受一个介于0到99之间的数字,然后是一个和另一个介于0和99之间的数字。
然后是 a p ,然后是 m
然后你有 Mon Tue 或....或 - for 1 to endles times。



最后你有修饰符 g
m 是利用 ^ $ 代表行的开始和结束的修饰符。
g 只是查找所有结果而不是第一个存在的结果。你可以把它放在外面。



使用一个名为 $ array 的数组来使用Weekdays只需简单地将它放入一个字符串中如下所示填入你的表达式:

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

阅读 implode


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?

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.