Php 突出显示文本中的搜索关键字

Php 突出显示文本中的搜索关键字,php,Php,我使用该类突出显示一段文本上的搜索关键字: class highlight { public $output_text; function __construct($text, $words) { $split_words = explode( " " , $words ); foreach ($split_words as $word) {

我使用该类突出显示一段文本上的搜索关键字:

    class highlight
    {
        public $output_text;

        function __construct($text, $words)
        {
            $split_words = explode( " " , $words );
            foreach ($split_words as $word)
            {
                $text = preg_replace("|($word)|Ui" ,
                           "<font style=\"background-color:yellow;\"><b>$1</b></font>" , $text );
            }
            $this->output_text = $text;
        }
    }
类突出显示
{
公共$output_text;
函数构造($text,$words)
{
$split_words=分解(“,$words);
foreach($word拆分为$word)
{
$text=preg_replace(“|($word)| Ui”,
“$1”,$text);
}
$this->output_text=$text;
}
}
如果 $text=“Khalil,M.,Paas,F.,Johnson,T.E.,Su,Y.K.,和Payer,A.F.(2008.)使用横截面的教学策略对相关CT和MR图像中解剖结构识别的影响。
解剖科学教育,1(2)
,75-83”

它已经包含HTML标记,我的一些搜索关键字是

$words=“效果颜色”

第一个循环将突出显示单词Effects,带有
Effects
,但第二个循环将突出显示HTML标记中的单词color。我该怎么办


是否可以告诉preg_replace仅在文本不在鳄鱼括号内时突出显示文本

使用a确保只搜索文本。

您可以使用CSS高亮显示的类,然后使用span标记,例如

<span class="highlighted">word</span>
word
然后在CSS中定义突出显示的类。然后,您可以排除“突出显示”一词在搜索中的有效性。当然,将类重命名为一些不知名的名称会有所帮助

这还有一个好处,即允许您在将来轻松更改突出显示颜色,或者允许用户通过修改CSS来打开和关闭突出显示颜色。

为什么要使用循环

    function __construct($text, $words) 
    { 
        $split_words = preg_replace("\s+", "|", $words); 
        $this->output_text = preg_replace("/($split_words)/i" , 
         "<font style=\"background-color:yellow; font-weight:bold;\">$1</font>" , $text ); 
    } 
function\u构造($text,$words)
{ 
$split_words=preg_replace(“\s+”、“|”、$words);
$this->output\u text=preg\u replace(“/($split\u words)/i”,
“$1”,$text);
} 

一种可能的解决方法是首先用字符将其包装,而字符(99%)不是搜索输入,并在“foreach”循环后用html标记替换这些字符:

class highlight
{
    public $output_text;

    function __construct($text, $words)
    {
        $split_words = explode(" ", $words);
        foreach ($split_words as $word)
        {
            $text = preg_replace("|($word)|Ui", "%$1~", $text);
        }

        $text = str_replace("~", "</b></span>", str_replace("%", "<span style='background-color:yellow;'><b>", $text));
        $this->output_text = $text;
    }
}
类突出显示
{
公共$output_text;
函数构造($text,$words)
{
$split_words=分解(“,$words);
foreach($word拆分为$word)
{
$text=preg_replace(“|($word)| Ui”、“%$1~”、$text);
}
$text=str_replace(“~”,“”,str_replace(“%”,“”,$text));
$this->output_text=$text;
}
}

CSS是一个很好的例子,但他的主要问题是他只想要文本,而不想要标签中的某些项目,即“aligator括号”。看看这个,肯定会对你有所帮助,