Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

highlight the word in the string, if it contains the keyword

Tags:

php

how write the script, which menchion the whole word, if it contain the keyword? example: keyword "fun", string - the bird is funny, result - the bird is * funny*. i do the following

     $str = "my bird is funny";      $keyword = "fun";      $str = preg_replace("/($keyword)/i","<b>$1</b>",$str); 

but it menshions only keyword. my bird is funny

like image 524
Simon Avatar asked Mar 20 '10 16:03

Simon


People also ask

How do you highlight words in PHP?

The highlight_string() function outputs a string with the PHP syntax highlighted. The string is highlighted by using HTML tags. The colors used for syntax highlighting can be set in the php.


1 Answers

Try this:

preg_replace("/\w*?$keyword\w*/i", "<b>$0</b>", $str) 

\w*? matches any word characters before the keyword (as least as possible) and \w* any word characters after the keyword.

And I recommend you to use preg_quote to escape the keyword:

preg_replace("/\w*?".preg_quote($keyword)."\w*/i", "<b>$0</b>", $str) 

For Unicode support, use the u flag and \p{L} instead of \w:

preg_replace("/\p{L}*?".preg_quote($keyword)."\p{L}*/ui", "<b>$0</b>", $str) 
like image 100
Gumbo Avatar answered Sep 28 '22 12:09

Gumbo