PHP检查复杂的字符串是否格式正确(PHP Check complicated String for correct format)

其他开发 IT屋
问 题

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.

本文地址:IT屋 » PHP Check complicated String for correct format

问 题



验证的格式是

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


示例条目可以是:

  8:55 pm [仅限周二至周四] 

code>


d [i] 表示一个关联数组的值,星期。
例如,上面包含星期六和星期日。

在插入数据库之前,我需要确认/验证这个数据。



我可以得到一些帮助吗?

解决方案

检查正则表达式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


本文地址:IT屋 » PHP检查复杂的字符串是否格式正确