preg_replace仅高亮匹配子串却替换整词的问题如何解决
问题原因
你写的正则中额外添加了前后的\p{L}*?和\p{L}*匹配规则,这两个规则会匹配搜索词前后所有连续的Unicode字母字符,因此会把包含搜索词的完整单词全部匹配到,最终导致整个单词都被高亮。
修正方案
直接匹配你传入的搜索字符串即可,不需要额外添加前后的字母匹配规则,同时建议给preg_quote传入第二个参数指定正则分隔符,避免搜索词包含/时正则抛出语法错误,修正后代码如下:
$result = preg_replace("/" . preg_quote($search, '/') . "/ui", "<strong style='color:yellow'>$0</strong>", $sentence);
效果验证
用你给出的示例测试:
$sentence = 'This is the sentence to be searhed through'; $search = 'sent'; echo $result;
输出结果为:This is the <strong style='color:yellow'>sent</strong>ence to be searhed through,完全符合预期效果。
内容的提问来源于stack exchange,提问作者Valiyor Irismetov
相关产品推荐
相关产品推荐

