I can highlight one word in string like this:
$str = "my bird is funny";
$keyword = "fun";
$str = preg_replace("/($keyword)/i","<b>$0</b>",$str);
Ant this will give me: my bird is funny
But how to make this work when keyword is from more than one word for example when
$keyword = "bird fun";
I would like to get this result: my bird is funnny
One of the most basic concepts of regular expressions is alternation. bird|fun will match either bird or fun. This alternation can easily be generated using implode and explode:
$keywords = explode(' ', trim($keyword));
$str = preg_replace('/'.implode('|', $keywords).'/i', '<b>$0</b>', $str);
As pritaeas pointed out, you could also use str_replace:
$str = preg_replace('/'.str_replace(' ', '|', trim($keywords)).'/i', '<b>$0</b>', $str);
Of course, if you write $keyword yourself and don't use it anywhere else then write it as a regex right away:
$keyword = 'bird|fun';
or even
$keyword = '/bird|fun/i';
This way you don't need any explode or implode at all.
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