Search code examples
phpregexcpu-wordhighlightphrase

Regex for highlighting phrase inside string


I had made this algorithm to highlight a word inside a string, but I must adapt it to also highlight a phrase.

What I had was a function that loop word by word, trim unwanted characters and replace using \b($str)\b.

I made that way so I could trim ",.-", etc.., for example, but that's not a good solution for phrases (not even for words).

How could I achieve this for phrases as well?

An example: suppose I have to highlight adipiscing elit in this string:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

It must become:

Lorem ipsum dolor sit amet, consectetur <span>adipiscing elit</span>.

Solution

  • I don't understand well but try this:

    \b(adipiscing elit\b\W?)
    

    and replacement string:

    <span>$1</span>
    

    Output in regexstorm.net:

    Lorem ipsum dolor sit amet, consectetur <span>adipiscing elit.</span>