我试图在
PHP中创建一个正则表达式,检查字符串是否符合以下规则:
>下列字符串之一(周一,周二,周三,周四,周五,周六,周日)有1-7次出现
>由a分隔的字符串,
>不区分大小写
>不重复任何字符串.
我相信我已经通过以下方式实现了前三个方面:
/^(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)(,(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)){0,6}$/i
我正在努力防止任何重复.任何人都可以建议吗?
^(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)(?:,(?!\1|\2)(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)){0,6}$
你可以使用这个,如果正则表达式是一个绝对的要求,但我宁愿推荐Martijn的答案.它更灵活,更易于阅读.
<?PHP $subject1 = "Mon,Mon"; $subject2 = "Sun,Mon,Fri,Sun"; $subject3 = "Sat"; $subject4 = "Mon,Wed,Tues,Wed"; $subject5 = "Mon,Tues"; $pattern = '/^(Mon|Tues|Wed|Thurs|Fri|Sat|Sun)(?:,6}$/i'; print_r(preg_match($pattern,$subject1,$matches) . " " . $subject1 . "\n"); print_r(preg_match($pattern,$subject2,$matches) . " " . $subject2 . "\n"); print_r(preg_match($pattern,$subject3,$matches) . " " . $subject3 . "\n"); print_r(preg_match($pattern,$subject4,$matches) . " " . $subject4 . "\n"); print_r(preg_match($pattern,$subject5,$matches) . " " . $subject5 . "\n"); ?>
这输出:
0 Mon,Mon 0 Sun,Sun 1 Sat 1 Mon,Wed 1 Mon,Tues