Reputation: 762
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
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
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