Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

highlight multiple words in string

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

like image 965
DadaB Avatar asked Feb 02 '26 08:02

DadaB


1 Answers

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.

like image 153
Martin Ender Avatar answered Feb 03 '26 21:02

Martin Ender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!