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
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With