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');
注意:str_ireplace是不区分大小写的版本str_replace。
也。。。显然,您需要在某处为"hilight"定义CSS!
您正在寻找preg_replace()
.
preg_replace('/'b(spoon)'b/i', '<span style="color:red;">$1</span>', $str);
DaveRandom的笔记:
'b
是一个单词边界断言,用于确保您不匹配茶匙或勺子,()
是在替换中使用的捕获组,因此大小写保持不变。
末尾的i
可确保不区分大小写,并且$1
会将匹配的单词放回替换字符串中。
你找不到"勺子",因为你会爆炸一个空格,所以你只会得到"勺子"。
您可以在一行中执行此操作:
str_replace("spoon", "<span style='"color:red;'">spoon</span>", $str);
希望这有帮助。
你的代码不起作用的原因是,当你在"(空格)上爆炸时,你希望收到一个带有单词"spoon"的数组,但实际上它是单词"spoon"。(注意句点)添加到数组中,以及为什么您的条件语句if ($array[$i] == "spoon")
永远不会触发。
注意:虽然我同意大多数人的观点,并认为他应该使用像str_replace或preg_replace这样的替代方案,但我认为必须说一些关于试图"从头开始"解决这个问题的事情。