How to wrap html tags for each search words, such as highlight words. I tried my code here, but nothing changed. Where is the problem, or is there have any other good way? thanks.
<?php
$sentence = "for loops are the most complex loops in PHP. They behave like their C counterparts";//original
$search = 'php counterparts';//search words
$str = explode(' ',$search);//explode every search word
for($i=0;$i<10;$i++){
if($str[$i]!=''){ //make sure if $str[$i] is not empty, do $newstr.
$newstr .= '\'<b>'.$str[$i].'</b>\','; //wrap <b> tag for search words
}
}
$newstr = substr($newstr, 0, strlen($newstr)-1);//remove last common, combine a array
$new = str_ireplace(array($str),array($newstr),$sentence);
echo $new;
?>
Why is the array bounded at 10 iterations? Why do you use a string to hold the modified words? Why the regex demarcations when your not using a regex function for the substitution?
Don’t even try to fix this code – start again from scratch: