我正在尝试从[两个日期都是动态的以下行中使用April 1, 2017
提取开始日期preg_match_all()
。
for April 1, 2017 to April 30, 2017
$contents = "for April 1, 2017 to April 30, 2017";
if(preg_match_all('/for\s(.*)+\s(.*)+,\s(.*?)+ to\s[A-Za-z]+\s[1-9]+,\s[0-9]\s/', $contents, $matches)){
print_r($matches);
}
如果要匹配整个字符串并匹配两个日期(如模式),则可以使用2个捕获组。
注意,它不会验证日期本身。
\bfor\h+(\w+\h+\d{1,2},\h+\d{4})\h+to\h+((?1))\b
部分
\bfor\h+
字边界,匹配for
和1+个水平空格字符(
捕获组1\w+\h+\d{1,2}
匹配1+个单词字符,1 +个水平空格字符和1或2位数字,\h+\d{4}
匹配逗号,1个以上水平空格字符和4个数字])
关闭组\h+to\h+
匹配to
在1个以上水平白色字符之间(
捕获第2组(?1)
Subroutine call捕获组1(与组1相同的模式,因为它具有相同的逻辑)])
关闭组\b
字边界例如
$re = '/\bfor\h+(\w+\h+\d{1,2},\h+\d{4})\h+to\h+((?1))\b/';
$str = 'for April 1, 2017 to April 30, 2017';
preg_match_all($re, $str, $matches);
print_r($matches)
输出
Array
(
[0] => Array
(
[0] => for April 1, 2017 to April 30, 2017
)
[1] => Array
(
[0] => April 1, 2017
)
[2] => Array
(
[0] => April 30, 2017
)
)