preg_quote忽略preg_match_all中的尾随点

时间:2016-10-19 08:12:33

标签: php regex preg-match-all preg-quote

正则表达式

preg_match_all('@(\b' . preg_quote($needle,'@') . '\b)@is', $haystack, $matches);

干草堆

(Job: NAS-Inkrementell) Operation succeeded.

Operation succeeded - >作品

Operation succeeded. - >不起作用

我做了一些测试:

替代干草堆

(Job: NAS-Inkrementell) Op.eration succeeded.

替代针

Op.eration succeeded - >作品

所以,针确实被正确转义,我可以通过dump(preg_quote($needle,'@'));看到 - > Operation succeeded\.

包含尾随点的正确方法是什么?

供快速参考:http://www.phpliveregex.com/p/hzl

由于

修改

当针头为My-NAS时,我还需要区分大海捞针中的My-NAS-2My-NAS,因此我也需要尾随\b

EDIT2

ideone.com/Suzz2E我希望它是1 1 0 1而不是1 1 1 1,因此如果大海捞针中只有MyNAS,则不应找到MyNAS-2

1 个答案:

答案 0 :(得分:1)

.不是单词字符,\.\b模式在.之后需要单词char。您需要实现自定义字边界。

由于您需要匹配前面没有单词char或连字符且未后跟单词char或连字符的字符串,您可以使用

preg_match_all('@(?<![\w-])' . preg_quote($needle1,'@') . '(?![\w-])@is', $haystack, $matches)

请参阅regex demo

请参阅PHP demo

$haystack1 = "(Job: NAS-Inkrementell) Operation succeeded. MyNAS-2 reports duty.";

$needle1 = "Operation succeeded";
echo preg_match_all('@(?<![\w-])' . preg_quote($needle1,'@') . '(?![\w-])@is', $haystack1, $matches1) ."\n";

$needle2 = "Operation succeeded.";
echo preg_match_all('@(?<![\w-])' . preg_quote($needle2,'@') . '(?![\w-])@is', $haystack1, $matches2) ."\n";

$needle3 = "MyNAS";
echo preg_match_all('@(?<![\w-])' . preg_quote($needle3,'@') . '(?![\w-])@is', $haystack1, $matches3) ."\n";

$needle4 = "MyNAS-2";
echo preg_match_all('@(?<![\w-])' . preg_quote($needle4,'@') . '(?![\w-])@is', $haystack1, $matches4) ."\n";