简体   繁体   中英

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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