我想在给定字符串中突出显示带有背景颜色的多个文本。
我正在使用此代码:
<style>
.highlight{
background: #CEDAEB;
}
</style>
<?
$str = 'Led Plant Lamp , nikeshoes, hid xenon lamps, torchs, xenon lamp, mp3, mp4, sola, glass';
$keywords = array("k span","htc","nike","tma","ass","ck","rei","bov");
$style = 'highlight';
foreach($keywords as $keyword)
{
$replacement = "<span class='".$style."'>".$keyword."</span>";
$str = str_ireplace($keyword, $replacement, $str);
}
return $str;
?>
Output:Led Plant Lamp , ass='highlight'>nikeshoes, hid xenon lamps, torchs, xenon lamp, mp3, mp4, sola, glass
str_ireplace函数用span类替换关键字ass。请帮助我在这段代码中错误的地方
答案 0 :(得分:1)
试试这个:
<style>
.highlight{
background: #CEDAEB;
}
</style>
<?
$str = 'Led Plant Lamp , nikeshoes, hid xenon lamps, torchs, xenon lamp, mp3, mp4, sola, glass';
$keywords = array("k span","htc","nike","tma","ass","ck","rei","bov");
$style = 'highlight';
$arr1 = array();
$input = $str;
$str = explode(" ",$str);
foreach($str as $index=>$strings)
{
for($i=0; $i<count($keywords); $i++)
{
if (stristr($strings, $keywords[$i]) !== false){
if(!isset($arr1[$index]))
{
$str_first_position = stripos($strings,$keywords[$i]);
$str_last_position = strlen($keywords[$i])-1 + $str_first_position;
$str_first_char = substr($strings,0,$str_first_position);
$str_last_char = substr($strings,$str_last_position+1,strlen($strings));
$arr1[$index] = $str_first_char."<span class='".$style."'>".$keywords[$i]."</span>".$str_last_char;
}
break;
}
}
}
$arr2 = $arr1+$str;
ksort($arr2);
return implode(" ",$arr2);
?>
答案 1 :(得分:-1)
试试这个:
<style>
.highlight{
background: #CEDAEB;
}
</style>
<?php
$str = "Led Plant Lamp , nikeshoes, hid xenon lamps, torchs, xenon lamp, mp3, mp4, sola, glass";
$keywords = array("ass", "k span", "htc", "nike","tma","ck","rei","bov");
$style = 'highlight';
foreach($keywords as $keyword)
{
$replacement = "<span class='highlight'>".$keyword."</span>";
$str = str_ireplace($keyword, $replacement, $str);
}
var_dump($str);
?>