DadaB
DadaB

Reputation: 762

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

Upvotes: 2

Views: 4396

Answers (3)

Mani
Mani

Reputation: 888

Try this:

<?
$str = "my bird is funny";
     $keyword= array("bird","fun");
     foreach($keyword as $k=>$v)
{
     $str = preg_replace("/($v)/i","<b>$0</b>",$str);
}
//echo $str;
?>

Upvotes: 1

Martin Ender
Martin Ender

Reputation: 44279

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.

Upvotes: 5

codaddict
codaddict

Reputation: 455272

$str = "my bird is funny";
$keyword = "bird fun";
$keyword = implode('|',explode(' ',preg_quote($keyword)));
$str = preg_replace("/($keyword)/i","<b>$0</b>",$str);

See it

Upvotes: 5

Related Questions