简体   繁体   English

如何在搜索突出显示关键字的preg_replace模式中添加/

[英]How to add / into the preg_replace pattern for search highlighting keyword

In the search script I use this function: 在搜索脚本中,我使用以下功能:

function highlightkeyword($string, $keyword, $color = '#DE6E08') 
{
    return preg_replace("/($keyword)/i", sprintf('<span style="color: #fff; background-color: %s; padding: 0 0.225rem;">$1</span>', $color), $string);} 

This should higlight searched word. 这应该是高亮搜索的单词。 But now I need to search for word: "FNPBH/E3" which contains forward slash. 但是现在我需要搜索包含正斜杠的单词:“ FNPBH / E3”。

This scripts finds the item but it does not display its name. 该脚本找到该项目,但不显示其名称。 It gives error as shown below. 出现如下所示的错误。

Warning: preg_replace(): Unknown modifier 'E' in line: 27

How to deal with it? 怎么处理呢? Any way of escaping? 有什么逃避方法吗?

在创建正则表达式之前,请使用preg_quote函数对$keyword进行转义。

Change up your start and end brackets. 更换您的开始和结束括号。 Instead of the forward slash / which is in your $keyword use a character you're not likely to find in your $keyword variable. 而不是在$keyword使用正斜杠/而不是在$keyword变量中不太可能找到的字符。 Like this: 像这样:

return preg_replace("!($keyword)!i", sprintf('<span style="color: #fff; background-color: %s; padding: 0 0.225rem;">$1</span>', $color), $string);

The exclamation points ! 感叹号! are now bracketing the regex. 现在将正则表达式括起来。 Currently, the forward slash in the $keyword is cutting off your regex. 当前, $keyword的正斜杠切断了您的正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM