PHP/CSS在字符串中查找单词,更改其颜色

win*_*f88 1 css php

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
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 5

您正在寻找preg_replace()

preg_replace('/\b(spoon)\b/i', '<span style="color:red;">$1</span>', $str);
Run Code Online (Sandbox Code Playgroud)

DaveRandom 的注释:

\b是一个字边界断言,以确保您不匹配 teaspoon 或 Spoonman,并且()是在替换中使用的捕获组,以便大小写保持不变。

i最后确保不区分大小写,并将$1匹配的单词放回替换字符串中。


Bri*_*ian 5

我个人会用:

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');
Run Code Online (Sandbox Code Playgroud)

注意: str_ireplace是不区分大小写的版本str_replace.

另外......显然你需要在某处为'hilight'定义css!