如何为每个搜索词(例如突出显示词)包装html标签。我在这里尝试了我的代码,但没有任何改变。问题出在哪里,或者还有什么其他好的方法?谢谢。
<?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;
?>
最佳答案
为什么数组以10次迭代为界?为什么使用字符串保存修改后的单词?当您不使用正则表达式函数进行替换时,为什么要用正则表达式划界呢?
甚至不要尝试修复此代码-从头开始:
$sentence = "for loops are the most complex loops in PHP. They behave like their C counterparts";//original
$search = 'php counterparts';//search words
$srch_words = explode(' ',$search);//explode every search word
$replace_words=array();
foreach ($srch_words as $key=>$val) {
$replace_words[$key]='<b>' . $val . '</b>';
}
$sentence=str_ireplace($srch_words, $replace_words, $sentence);