preg-replace 的问题:函数替换整个字符串而不是仅替换它的一部分

Problem with preg-replace: function replaces whole string instead of only part of it

我有一个未破案。我需要突出显示 $sentence 中的一些 $search 文本。

$result=preg_replace("/\p{L}*?".preg_quote($search)."\p{L}*/ui", "<strong style='color:yellow'>[=10=]</strong>", $sentence);

这个函数什么都好,找到子字符串的每一个出现,但它不仅突出显示(替换)单词中包含子字符串的部分,而且突出显示整个单词(从空格到空格)。

例如:

$sentence='This is the sentence to be searhed through';
$search = 'sent';
echo $result gives "This is the **sentence** to be searhed through"

但是我需要

"This is the sentence to be searhed through"

有人可以帮助我理解我做错了什么吗?提前致谢。

\p{L}*?\p{L}*? 匹配零个或多个字母(第一个是第二个的惰性变体),因此,您匹配任何包含 $search.[= 的单词18=]

你可以用

修复它
$sentence='This is the sentence to be searhed through';
$search = 'sent';
$result = preg_replace("/" . preg_quote($search, "/") . "/ui", "<strong style='color:yellow'>[=10=]</strong>", $sentence);
echo $result;
// => This is the <strong style='color:yellow'>sent</strong>ence to be searhed through

PHP demo

包含模式的 \p{L} 都被删除,preg_quote 也转义正则表达式定界符,请参阅此函数的 / 第二个参数。