【问题标题】:Problem with preg-replace: function replaces whole string instead of only part of itpreg-replace 的问题:函数替换整个字符串而不是仅替换其中的一部分
【发布时间】:2021-08-14 14:06:23
【问题描述】:

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

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

这个函数做得很好,找到子字符串的每一个出现,但它不仅突出显示(替换)包含子字符串的单词部分,还突出显示(替换)整个单词(从 whitespase 到空白)。

例如:

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

但我需要

“这是发送要被搜索的内容”

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

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

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

    你可以修复它

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

    PHP demo

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

    【讨论】:

      猜你喜欢
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 2019-08-06
      • 2019-05-31
      • 1970-01-01
      相关资源
      最近更新 更多