PHP/CSS 在字符串中查找单词,更改其显示颜色。遇到问题,找不到解决方案,有什么建议吗?谢谢。
<pre>
<?php
$str="Try to realize the truth... there is no spoon."; // spoon can be anywhere in string
$array = explode(" ", $str);
for($i=0;$i < count($array);$i++)
{
if ($array[$i] == "spoon") {
?><span style="color:red;"><?php echo echo $array[$i]." "; ?></span>
<?php
} else {
echo $array[$i]." ";
}
} ?>
</pre
我个人会使用:
function highlight($text='', $word='')
{
if(strlen($text) > 0 && strlen($word) > 0)
{
return (str_ireplace($word, "<span class='hilight'>{$word}</span>", $text));
}
return ($text);
}
$str="Try to realize the truth... there is no spoon."; // spoon can be anywhere in string
$str= highlight($str, 'spoon');
Note:str_ireplace 是不区分大小写的版本str_replace。
另外......显然你需要在某个地方定义'hilight'的CSS!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)