You need to enable JavaScript to run this app. preg_replace仅高亮匹配子串却替换整词的问题如何解决
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 21:54:01