1

I want to highlight my keyword search text by using preg_replace in php but the problem is it won't work with parentheses string ( and )

My function look like this...

$text_oritinal = "25 Hours: Colour In White (CD)";

function highlight($text_search, $text_original) {
  $str = preg_replace('#'. $text_search .'#i', '<span style="background-color:#FFFF66; color:#FF0000;">\\0</span>', $text_original);
  return $str;
}

Full original text is "25 Hours: Colour In White (CD)"

For example. If I use the keyword

$text_search = "25 Hours: Colour In White";

It return good replaced keyword with highlight background and text color.

<span style="background-color:#FFFF66; color:#FF0000;">25 Hours: Colour In White</span> (CD)

but! if I use this keyword included parentheses string ( and )

$text_search = "25 Hours: Colour In White (CD)";

It NOT return replaced background and text color.

I think it stuck with parentheses string ( and )

The question is how to highlight all text keyword matched without any problem with parentheses string ( and )?

Please share your idea. Thanks :)

2
  • 1
    Do not remove your question when editing. It makes asking the question useless. Commented Aug 6, 2012 at 14:53
  • I will do as your comment. Thank you. Commented Aug 6, 2012 at 15:10

2 Answers 2

3

You should call preg_quote:

function highlight($text_highlight, $text_search) {
  $str = preg_replace('#'. preg_quote($text_highlight) .'#i', '<span style="background-color:#FFFF66; color:#FF0000;">\\0</span>', $text_search);
  return $str;
}

Explanation:

Parenthesis are used to create submatches. Using them in your search string, will cause undesired results as they are reserved characters. You can prevent this, and other characters by using preg_quote which escapes regex reserved characters.

Sign up to request clarification or add additional context in comments.

Comments

0

Wrap the text you put into the regex in preg_quote

http://php.net/manual/en/function.preg-quote.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.