Highlight keywords in a paragraph

前端 未结 7 1582
梦如初夏
梦如初夏 2020-11-29 13:40

I need to highlight a keyword in a paragraph, as google does in its search results. Let\'s assume that I have a MySQL db with blog posts. When a user searches for a certain

相关标签:
7条回答
  • 2020-11-29 14:37

    I found this post when doing a search for how to highlight keyword search results. My requirements were:

    • Must be whole words
    • Must work for more than one keyword
    • Must be PHP only

    I am fetching my data from a MySQL database, which doesn't contain elements, by design of the form which stores the data.

    Here is the code I found most useful:

    $keywords = array("fox","jump","quick");
    $string = "The quick brown fox jumps over the lazy dog";
    $test = "The quick brown fox jumps over the lazy dog"; // used to compare values at the end.
    
    if(isset($keywords)) // For keyword search this will highlight all keywords in the results.
        {
        foreach($keywords as $word)
            {
            $pattern = "/\b".$word."\b/i";
            $string = preg_replace($pattern,"<span class=\"highlight\">".$word."</span>", $string);
            }
        }
     // We must compare the original string to the string altered in the loop to avoid having a string printed with no matches.
    if($string === $test)
        {
        echo "No match";
        }
    else
        {
        echo $string;
        }
    

    Output:

    The <span class="highlight">quick</span> brown <span class="highlight">fox</span> jumps over the lazy dog.
    

    I hope this helps someone.

    0 讨论(0)
提交回复
热议问题