开发者

highlight search keywords in text

I am using this class to highlight the search keywords on a piece of text:

    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;
        }
    }

If $text = "Khalil, M., Paas, F., Johnson, T.E., Su, Y.K., and Payer, A.F. (2008.) Effects of Instructional Strategies Using Cross Sections on the Recognition of Anatomical Struc开发者_JS百科tures in Correlated CT and MR Images. <i>Anatomical Sciences Education, 1(2)</i>, 75-83 "

which already contains HTML tags, and some of my search keywords are

$words = "Effects color"

The first look will highlight the word Effects, with <font style="background-color:yellow">Effect</font>, but the second loop will highlight the word color in the HTML tag. What should I do?

Is it possible to tell preg_replace to only highlight text when its not inside an alligator bracket?


Use a HTML parser to make sure that you only search through text.


You could use a CSS highlighted class instead and then use span tags, eg.

<span class="highlighted">word</span>

Then define your highlighted class in CSS. You could then exclude the word 'highlighted' from being valid in your search. Of course renaming the class to something obscure would help.

This also has the benefit of allowing you to change the highlight colour easily in the future, or indeed allowing the user to toggle it on and off by modifying the CSS.


Why use a loop?

    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 ); 
    } 


A possible work-around would be to first wrap it with characters, which would (to 99%) not be a search input and replace those characters with the html tags after the 'foreach' loop:

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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜