1

I'm using this function from here, which is:

// highlight search keywords 
function highlight($title, $search) {
preg_match_all('~\w+~', $search, $m);
if(!$m)
    return $title;
    $re = '~\\b(' . implode('|', $m[0]) . ')\\b~i';

return preg_replace($re, '<span style="background-color: #ffffcc;">$0</span>', $title);
}

Which works great, but only for titles. I want to be able to pass an array that contains $title and $description.

I was trying something like this:

$replacements = array($title, $description);

// highlight search keywords 
function highlight($replacements, $search) {
preg_match_all('~\w+~', $search, $m);
if(!$m)
    return $replacements;
    $re = '~\\b(' . implode('|', $m[0]) . ')\\b~i';

return preg_replace($re, '<span style="background-color: #ffffcc;">$0</span>', $replacements);
}

It isn't working. It's passing an array as the title, and not highlighting the description (although it is actually returning a description). Any idea how to get this working?

Community
  • 1
  • 1
bob_cobb
  • 2,229
  • 11
  • 49
  • 109
  • Your [indentation](http://en.wikipedia.org/wiki/Indent_style) looks messed up. Please fix it. – outis Apr 30 '11 at 09:25

2 Answers2

2

I would personally leave the original function as only operating on one parameter rather than an array. It would make your calling code nice and clear;

$titleHighlighted = highlight($title, $searchKeywords);
$descriptionHighlighted = highlight($title, $searchKeywords);

However, I would rewrite your function to use str_ireplace rather than preg_replace;

function highlight($contentBlock, array $keywords) {
        $highlightedContentBlock = $contentBlock;

        foreach ($keywords as $singleKeyword) {
                $highlightedKeyword = '<span class = "keyword">' . $singleKeyword . '</span>';
                $highlightedContentBlock = str_ireplace($singleKeyword, $highlightedKeyword, $highlightedContentBlock);
        }   

        return $highlightedContentBlock;
}

This rewritten function should be more simple to read and does not have the overhead of compiling the regular expressions. You can call it as many times as you like for any content block (title, description, etc);

$title = "The quick brown fox jumper over ... ";

$searchKeywords = array("quick", "fox");
$titleHighlighted = highlight($title, $searchKeywords);

echo $titleHighlighted; // The <span class = "keyword">quick</span> brown ...
xconspirisist
  • 1,451
  • 2
  • 13
  • 26
  • Thank you so much for the help and the heads up that str_ireplace() is quicker than a regex. – bob_cobb Apr 30 '11 at 18:31
  • This will not work for search queries like "a a", because the keywords are "a" and "a" and for the first keyword the html will look like "a", and for next keyword "a" it will destroy the HTML and will provide "an> ..." it will actually replace the "a" contained in "" string also.. – Kevindra Nov 23 '11 at 08:52
0

have you try to change ?

$m[0]

with

$m[0][0]
Imam Mubin
  • 294
  • 2
  • 10