我有一个表单输入,用户可以按以下格式填写其餐厅的营业时间(存储在数据库中):
Fri 12-02, Sat 15-03
我需要一个正则表达式来验证他们的输入。
从评论中更新:
模式是:
3 character DayOfWeek
,[space]
,the opening hour (24 hour)
,[hyphen]
,the closing hour (24 hour)
嗯,这是几天的开放时间('周五')和时间('12 -02',如在12:00到02:00)。它应该拒绝任何理想情况下不符合相同模式的东西。所以
答案 0 :(得分:2)
具有命名模式的正则表达式:
/(?P<day>Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:-(?P<today>Mon|Tue|Wed|Thu|Fri|Sat|Sun))?\s+(?P<from>(?<=\s)(?:(?:2[0-3])|(?:[01]?[0-9]))(?:\:[0-5][0-9])?)-(?P<till>(?<=-)(?:(?:2[0-3])|(?:[01]?[0-9]))(?:\:[0-5][0-9])?)/g
它匹配所有这些:“星期五12-02,星期六15:30-03,星期一12-02,星期一15-03,星期一8:30-16:45”并给你一个带有命名键的数组(白天,今天,从,直到)。
您必须将preg_match_all
与PREG_SET_ORDER
一起使用。
示例输出:
array(
array(
'day' => 'Fri',
'from' => '12',
'till' => '02'
), array(
'day' => 'Sat',
'from' => '15:30',
'till' => '03'
), array(
'day' => 'Mon',
'from' => '12',
'till' => '02'
), array(
'day' => 'Mon',
'from' => '15',
'till' => '03'
), array(
'day' => 'Mon',
'today' => 'Thu',
'from' => '8:30',
'till' => '16:45'
)
);
至少我不确定它是PREG_SET_ORDER
还是PREG_PATTERN_ORDER
只是尝试一下。
答案 1 :(得分:1)
仅匹配3 letter days
,然后匹配[space]
,然后24hour time
,然后-
,然后24hour time
(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s([2][0-4]|[0-1][0-9])-([2][0-4]|[0-1][0-9])
匹配度:
Fri 12-12
Sat 23-22
不匹配:
Jpg 12-12
Sat 25-22
答案 2 :(得分:0)
答案 3 :(得分:0)
什么是有效且无效的btw?
另外,我们在看哪些领域?文字字段?
我的正则表达式:
/[0-9]{2}-[0-9]{2}/
它只能验证数字部分(即12-02)和Fri,可以在下拉菜单中。
如果没有,/[A-Z][a-z]{2} [0-9]{2}-[0-9]{2}/
...
请注意,这不会验证实际的数字时间值,它只会根据示例的格式验证格式。
答案 4 :(得分:0)
很难编写一个正则表达式,正确验证所有可能的日期格式。将作业留给日期解析器,这是为了这个目的而编写的。以下是使用DateTime
类来完成此任务的方法:
function customValidate($str, $format='D d-m')
{
// explode the string, remove whitespace
list($date1,$date2) = array_map('trim', explode(',', $str));
// parse them into DateTime objects
$d1 = DateTime::createFromFormat($format, $date1);
$d2 = DateTime::createFromFormat($format, $date2);
// check if they're valid
$d1f = $d1->format($format) == $date1;
$d2f = $d2->format($format) == $date2;
// return the boolean result
return $d1 && $d2 && $d1f && $d2f;
}