KRA
KRA

Reputation: 381

highlight only typed keywords from string in php

I am using following function to highlight searched keywords from string. It's working fine but having little issue.

$text="This is simple test text";
$words="sim text";
echo highlight($text, $words);

Using following function it is highlighting both "simple" & "text" words where I want it should highlight "sim" & "text" words only. What type of changes I need to make to achieve this result. Please advise.

function highlight($text, $words) 
{
    if (!is_array($words)) 
    {
        $words = preg_split('#\\W+#', $words, -1, PREG_SPLIT_NO_EMPTY);
    }
    $regex = '#\\b(\\w*(';
    $sep = '';
    foreach ($words as $word) 
    {
        $regex .= $sep . preg_quote($word, '#');
        $sep = '|';
    }
    $regex .= ')\\w*)\\b#i';
    return preg_replace($regex, '<span class="SuccessMessage">\\1</span>', $text);
}

Upvotes: 0

Views: 820

Answers (2)

Dogbert
Dogbert

Reputation: 222268

You need to capture all the relevant texts into groups for this.

Complete code: (I've marked lines which I have changed.)

$text="This is simple test text";
$words="sim text";
echo highlight($text, $words);

function highlight($text, $words)
{
    if (!is_array($words))
    {
        $words = preg_split('#\\W+#', $words, -1, PREG_SPLIT_NO_EMPTY);
    }
    # Added capture for text before the match.
    $regex = '#\\b(\\w*)(';
    $sep = '';
    foreach ($words as $word)
    {
        $regex .= $sep . preg_quote($word, '#');
        $sep = '|';
    }
    # Added capture for text after the match.
    $regex .= ')(\\w*)\\b#i';
    # Using \1 \2 \3 at relevant places.
    return preg_replace($regex, '\\1<span class="SuccessMessage">\\2</span>\\3', $text);
}

Output:

This is <span class="SuccessMessage">sim</span>ple test <span class="SuccessMessage">text</span>

Upvotes: 1

Pugazhenthi
Pugazhenthi

Reputation: 90

Hi dont use php to highlight search words its takes some times to find and replace each word.

Use jquery it will be easier then php.

Simple example:

function highlight(word, element) {
var rgxp = new RegExp(word, 'g');
var repl = '<span class="yourClass">' + word + '</span>';
element.innerHTML = element.innerHTML.replace(rgxp, repl); }

highlight('dolor');

I hope it will help full.

Upvotes: 0

Related Questions