Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

regex - 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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...