0

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?

W. Kowalik
  • 13
  • 6
  • Possible duplicate of [Escaping a forward slash in a regular expression](https://stackoverflow.com/questions/6076229/escaping-a-forward-slash-in-a-regular-expression) –  Nov 09 '17 at 04:22

2 Answers2

0

Use the preg_quote function to escape $keyword before creating your regex.

John Ellmore
  • 2,209
  • 1
  • 10
  • 22
0

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.

CodeMilitant
  • 140
  • 8
  • yes, it will work. SO should I use your solution or $keyword = preg_quote($keyword, '/'); before function – W. Kowalik Nov 09 '17 at 05:00
  • My solution offers a wider range of choices for your `$keyword` variable. For example, you have to tell preg_quote which character you want it to ignore. My solution by passes all these requirements and as long as your `$keyword` does not contain an `!` exclamation point, then you're going to get all possible results every time. If this works for you, please mark my answer as the solution. Thank you! – CodeMilitant Nov 09 '17 at 22:07