gpt4 book ai didi

php 如何为每个搜索词包装 html 标签,

转载 作者:行者123 更新时间:2023-12-03 22:57:35 25 4
gpt4 key购买 nike

如何为每个搜索词包裹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);

关于php 如何为每个搜索词包装 html 标签,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7793086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com