tags:

views:

104

answers:

5

i need the following -

if i have a sentence

$str = "i like programming very much";

and i search for a word

$word = "r";

i expect it to return the sentence

"i like programing very much"

I wrote the following regex for it, but it sometimes doesn't work.

$str = preg_replace("/([^\s{".preg_quote($word)."}]*?)(".preg_quote($word).")([^\s{".preg_quote($word)."}]*)/siu","<span class='pice1'>$1</span><span class='pice2'>$2</span><span class='pice1'>$3</span>",$str);

Could you tell me what i wrote wrong?

Thanks

UPDATE:

for example it doesn't work when

$str = "ameriabank"; and $word = "ab";

...

+2  A: 
$str = "i like programming very much";
$w = "r";
echo preg_replace("/($w)/", "<b>$1</b>", $str);

Output:

i like p<b>r</b>og<b>r</b>amming ve<b>r</b>y much

Answer to the comment: do it in two steps.

$str = "i like programming very much ready tear";
$w = "r";
$str = preg_replace("/\\b((?:\\w+|\\b)$w(\\w+|\\b))\\b/", "<i>$1</i>", $str);
$str = preg_replace("/($w)/", "<b>$1</b>", $str);
echo $str;

output:

i like <i>p<b>r</b>og<b>r</b>amming</i> <i>ve<b>r</b>y</i> much <i><b>r</b>eady</i> <i>tea<b>r</b></i>
Amarghosh
what about other parts of word `programming`? i need to highlight them too, but in other way(not bold i mean)...
Syom
@Syom see the update
Amarghosh
+2  A: 

Why dont't you just use str_replace()? I think it's more simple

$search = "ab";
$word = "ameriabank";
$newstr = "<span class=\"pice1\">".str_replace($search, $word, "</span><span class=\"pice3\">".$search."</span></span class=\"pice1>\")."</span>";
Tokk
it will not work with big amount of text...
Syom
but thanks much:)
Syom
+1  A: 

visit http://stackoverflow.com/questions/2757556/highlight-multiple-keywords-in-search and be amazed.

Ian
+2  A: 

What about this way :

$str = "i like programming very much";
$word = "r";
$list = explode(' ',$str);
for($i=0; $i<count($list); $i++) {
    if(preg_match("/$word/", $list[$i])) {
        $list[$i] = '<i>'.preg_replace("/$word/siu", "<b>$word</b>", $list[$i]).'</i>';
    }
}
$str = implode(' ',$list);
echo $str,"\n";
M42
+1  A: 
$str = "i like programming very much";
$word = "r";
function highlight($matches)
{
    global $word;
    return '<span class="pice1">'.str_replace($word,'<span class="pice2">'.$word.'</span>',$matches[0]).'</span>';
}
echo $str = preg_replace_callback("/([^\s]*?".preg_quote($word, '/')."[^\s]*)/siu", highlight, $str);

do the job(and it works with foreign languages too)...

Syom