【问题标题】:How to highlight matched part of a string in php如何在php中突出显示字符串的匹配部分
【发布时间】:2016-12-03 11:01:09
【问题描述】:

这是我当前在 php 中的函数:

function highlight_keywords($keyword, $string) {
    return preg_replace("/\p{L}*?".preg_quote($keyword)."\p{L}*/ui", "<span class=\"h\">$0</span>", $string);
}

css 类:

span.h {
    font-weight: 700;
    color: @color_action;
}

例子:

echo highlight_keywords('anto', 'Andres Santos');

问题是结果是:

Andres <span class="h">Santos</span>

...应该是:

Andres S<span class="h">anto</span>s

【问题讨论】:

  • 为什么会有 \p{L}*?模式的一部分?为什么不只是return preg_replace("/".preg_quote($keyword)."/ui", "&lt;span class=\"h\"&gt;$0&lt;/span&gt;", $string);
  • @BrandonHorsley 你是对的。您的回答比下面的第一个回答还要简单。
  • 无需使用正则表达式来匹配静态值。使用return str_replace($keyword, '&lt;span class="h"&gt;' . $keyword . '&lt;/span&gt;', $string);
  • @chris85 是正确的,str_ireplace 如果您需要不区分大小写。
  • 我可能错了,但是 str_replace 在返回特殊字符时并不总是很好。

标签: php regex preg-replace highlighting


【解决方案1】:

使用捕获组:

function highlight_keywords($keyword, $string) {
    return preg_replace("/(\p{L}*?)(".preg_quote($keyword).")(\p{L}*)/ui", "$1<span class=\"h\">$2</span>$3", $string);
}

【讨论】:

    【解决方案2】:

    我同意@chris85 的评论。您没有理由为此任务使用正则表达式。

    只需将文字字符串替换为标签包装的文字字符串即可。

    return str_replace($keyword, '<span class="h">' . $keyword . '</span>', $string);
    

    如果您需要不区分大小写的支持,那么我同意 @BrandoneHorsley 的观点,即 str_ireplace() 就足够了。

    return str_ireplace($keyword, '<span class="h">' . $keyword . '</span>', $string);
    

    至于您对特殊字符的关注,我们亲爱的@deceze has this to say/demonstrate as the highest voted comment in the php docs

    请注意所有关于 mb_str_replace 的讨论 cmets 是毫无意义的。 str_replace 与 多字节字符串

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 2018-09-22
      • 2015-03-06
      • 1970-01-01
      • 2012-08-09
      相关资源
      最近更新 更多