我有一个函数,它使用preg_match来检查子字符串是否在另一个字符串中。 今天我意识到如果substring有特殊正则表达式字符(。\ + *?[^] $(){} =!<> |: - )或@的特殊字符,我的preg_match无法找到子串即使它在那里。
这有效,返回"找到匹配。"
$find = "website scripting";
$string = "PHP is the website scripting language of choice.";
if (preg_match("/\b" . $find . "\b/i", $string)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
但是这并没有,返回"找不到匹配。"
$find = "website scripting @";
$string = "PHP is the website scripting @ language of choice.";
if (preg_match("/\b" . $find . "\b/i", $string)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
我尝试了preg_quote,但它没有帮助。
感谢您的任何建议!
编辑:需要字边界,这就是我使用\ b的原因。我不想找到"电话"在"智能手机"。
答案 0 :(得分:3)
您可以检查搜索词周围的字符是否不是带有环视的字词:
$find = "website scripting @";
$string = "PHP is the website scripting @ language of choice.";
if (preg_match("/(?<!\\w)" . preg_quote($find, '/') . "(?!\\w)/i", $string)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
请参阅IDEONE demo
结果:A match was found.
请注意\w
和(?<!\\w)
中(?!\\w)
使用的双斜杠,因为您必须在插值字符串中转义正则表达式特殊字符。
preg_quote
函数是必要的,因为搜索词 - 从我看到的 - 可以有特殊字符,如果要匹配为文字字符,必须对其中一些字符进行转义。
<强>更新强>
有一种方法可以在关键字周围使用智能放置的字边界构建正则表达式,但与上述方法相比,性能会更差。以下是示例代码:
$string = "PHP is the website scripting @ language of choice.";
$find = "website scripting @";
$find = preg_quote($find);
if (preg_match('/\w$/u', $find)) { // Setting trailing word boundary
$find .= '\\b';
}
if (preg_match('/^\w/u', $find)) { // Setting leading word boundary
$find = '\\b' . $find;
}
if (preg_match("/" . $find . "/ui", $string)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
答案 1 :(得分:0)
如果您尝试从其他字符串中查找字符串,则可以strpos()
。
实施例。
<?php
$find = "website scripting";
$string = "PHP is the website scripting language of choice.";
if (strpos($string,$find) !== false) {
echo 'true';
} else {
echo 'false';
}