使用preg_match匹配此特定模式

时间:2016-05-29 05:05:51

标签: php regex preg-match

我对特定模式有一个preg_match匹配,但它与我尝试匹配的模式不匹配。我究竟做错了什么?

<?php

$string = "tell me about cats";
preg_match("~\b(?:tell me about|you know(?: of| about)?|what do you think(?: of| about)?|(?:what|who) is|(?:whats|whos)) ((?:[a-z]+ ){1,2})$~", $string, $match);
print_r($match);

?>

预期结果:

数组(0 =&gt;告诉我关于1 =&gt;猫)

实际结果:

阵列()

1 个答案:

答案 0 :(得分:2)

中有一个额外的空格(cat使整个正则表达式失败后没有空格)

((?:[a-z]+ ){1,2})
          ^^
          ||
         here

另外,您没有第一部分(由于(?:..)的捕获组。使用? 创建一个捕获组并使空格可选(如果您想捕获最多两个单词)

\b(tell me about|you know(?: of| about)?|what do you think(?: of| about)?|(?:what|who) is|(?:whats|whos)) ((?:[a-z]+){1,2} ?)$

<强> Regex Demo

PHP代码

$string = "tell me about cats";
preg_match("~\b(tell me about|you know(?: of| about)?|what do you think(?: of| about)?|(?:what|who) is|(?:whats|whos)) ((?:[a-z]+ ?){1,2})$~", $string, $match);
print_r($match);

注意: - $match[1]$match[2]将包含您的结果。 $match[0]保留用于字符串中正则表达式找到的整个匹配。

<强> Ideone Demo