Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3309346
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T21:37:47+00:00 2026-05-17T21:37:47+00:00

I need to highlight a keyword in a paragraph, as google does in its

  • 0

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 keyword I wish to return the posts which contain those keywords, but to show only parts of the posts (the paragraph which contain the searched keyword) and to highlight those keywords.

My plan is this:

  • find the post id which has the searched keyword in it’s content;
  • read the content of that post again and put each word in a fixed buffer array (50 words) until I find the keyword.

Can you help me with some logic, or at least to tell my if my logic is ok? I’m in a PHP learning stage.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T21:37:48+00:00Added an answer on May 17, 2026 at 9:37 pm

    If it contains html (note that this is a pretty robust solution):

    $string = '<p>foo<b>bar</b></p>';
    $keyword = 'foo';
    $dom = new DomDocument();
    $dom->loadHtml($string);
    $xpath = new DomXpath($dom);
    $elements = $xpath->query('//*[contains(.,"'.$keyword.'")]');
    foreach ($elements as $element) {
        foreach ($element->childNodes as $child) {
            if (!$child instanceof DomText) continue;
            $fragment = $dom->createDocumentFragment();
            $text = $child->textContent;
            $stubs = array();
            while (($pos = stripos($text, $keyword)) !== false) {
                $fragment->appendChild(new DomText(substr($text, 0, $pos)));
                $word = substr($text, $pos, strlen($keyword));
                $highlight = $dom->createElement('span');
                $highlight->appendChild(new DomText($word));
                $highlight->setAttribute('class', 'highlight');
                $fragment->appendChild($highlight);
                $text = substr($text, $pos + strlen($keyword));
            }
            if (!empty($text)) $fragment->appendChild(new DomText($text));
            $element->replaceChild($fragment, $child);
        }
    }
    $string = $dom->saveXml($dom->getElementsByTagName('body')->item(0)->firstChild);
    

    Results in:

    <p><span class="highlight">foo</span><b>bar</b></p>
    

    And with:

    $string = '<body><p>foobarbaz<b>bar</b></p></body>';
    $keyword = 'bar';
    

    You get (broken onto multiple lines for readability):

    <p>foo
        <span class="highlight">bar</span>
        baz
        <b>
            <span class="highlight">bar</span>
        </b>
    </p>
    

    Beware of non-dom solutions (like regex or str_replace) since highlighting something like “div” has a tendency of completely destroying your HTML… This will only ever “highlight” strings in the body, never inside of a tag…


    Edit Since you want Google style results, here’s one way of doing it:

    function getKeywordStubs($string, array $keywords, $maxStubSize = 10) {
        $dom = new DomDocument();
        $dom->loadHtml($string);
        $xpath = new DomXpath($dom);
        $results = array();
        $maxStubHalf = ceil($maxStubSize / 2);
        foreach ($keywords as $keyword) {
            $elements = $xpath->query('//*[contains(.,"'.$keyword.'")]');
            $replace = '<span class="highlight">'.$keyword.'</span>';
            foreach ($elements as $element) {
                $stub = $element->textContent;
                $regex = '#^.*?((\w*\W*){'.
                     $maxStubHalf.'})('.
                     preg_quote($keyword, '#').
                     ')((\w*\W*){'.
                     $maxStubHalf.'}).*?$#ims';
                preg_match($regex, $stub, $match);
                var_dump($regex, $match);
                $stub = preg_replace($regex, '\\1\\3\\4', $stub);
                $stub = str_ireplace($keyword, $replace, $stub);
                $results[] = $stub;
            }
        }
        $results = array_unique($results);
        return $results;
    }
    

    Ok, so what that does is return an array of matches with $maxStubSize words around it (namely up to half that number before, and half after)…

    So, given a string:

    <p>a whole 
        <b>bunch of</b> text 
        <a>here for</a> 
        us to foo bar baz replace out from this string
        <b>bar</b>
    </p>
    

    Calling getKeywordStubs($string, array('bar', 'bunch')) will result in:

    array(4) {
      [0]=>
      string(75) "here for us to foo <span class="highlight">bar</span> baz replace out from "
      [3]=>
      string(34) "<span class="highlight">bar</span>"
      [4]=>
      string(62) "a whole <span class="highlight">bunch</span> of text here for "
      [7]=>
      string(39) "<span class="highlight">bunch</span> of"
    }
    

    So, then you could build your result blurb by sorting the list by strlen and then picking the two longest matches… (assuming php 5.3+):

    usort($results, function($str1, $str2) { 
        return strlen($str2) - strlen($str1);
    });
    $description = implode('...', array_slice($results, 0, 2));
    

    Which results in:

    here for us to foo <span class="highlight">bar</span> baz replace out...a whole <span class="highlight">bunch</span> of text here for 
    

    I hope that helps… (I do feel this is a bit… bloated… I’m sure there are better ways to do this, but here’s one way)…

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to write some code that performs an HTML highlight on specific keywords
I just need to highlight a div by changing its background color for just
I need to highlight, case insensitively, given keywords in a JavaScript string. For example:
I basically need to highlight a particular word in a block of text. For
I'm working on an asp.net application which uses Lucene.net I need to highlight the
Need a function that takes a character as a parameter and returns true if
Need to an expression that returns only things with an I followed by either
need ask you about some help. I have web app running in Net 2.0.
Need a function like: function isGoogleURL(url) { ... } that returns true iff URL
I am building a 'keyword' highlighting script and I need to write a regular

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.