user2117559
user2117559

Reputation: 15

Highlight search results - whole expressions and single words

I want highlight whole expresions and single words

$text ="text text aaa bbb ccc text aaa text xxaaayy text bbb ccc text bbb cccxxx text";
$words = array('aaa bbb ccc','aaa bbb','bbb ccc','aaa','bbb','ccc');
foreach ($words as $k=>$v){
  $text = preg_replace('/(\w*?'.$v.'\w*)/i', '[b]$1[/b]', $text);
}

this code will return:

text text [b][b]aaa[/b] [b]bbb[/b] [b]ccc[/b][/b] text [b]aaa[/b] text [b]xxaaayy[/b] text [b][b]bbb[/b] [b]ccc[/b][/b] text [b][b]bbb[/b] [b]cccxxx[/b][/b] text

how to get this result:

text text [b]aaa bbb ccc[/b] text [b]aaa[/b] text [b]xxaaayy[/b] text [b]bbb ccc[/b] text [b]bbb cccxxx[/b] text

how to modify preg_replace ?

Upvotes: 0

Views: 193

Answers (1)

Shehabic
Shehabic

Reputation: 6877

There you go :

<?php

$text ="text text aaa bbb ccc text aaa text xxaaayy text bbb ccc text bbb cccxxx text";
$words = array('aaa bbb ccc','aaa bbb','bbb ccc','aaa','bbb','ccc');
$text = preg_replace('/('.implode("|",$words).')/i', '[b]$1[/b]', $text);
echo $text;

?>

UPDATED Version:

<?php

$text ="text text aaa bbb ccc text aaa text xxaaayy text bbb ccc text bbb cccxxx text";
$words = array('aaa bbb ccc','aaa bbb','bbb ccc','aaa','bbb','ccc');
$text = preg_replace('/(\w*('.implode("|",$words).')\w*)/i', '[b]$1[/b]', $text);
echo $text;

?>

Upvotes: 1

Related Questions