Highlight search results using the string part

I use the following code to highlight search results:

$text = preg_replace("/\b($word)\b/i", '<span class="highlight_word">\1</span>', $text); 

and its performance.

But preg_replace returns a whole line and highlights the words that match.

I need to get part of the string and only the whole string.

The scenario is to get 100 characters up to 100 characters after the first match. Any help would be appreciated.

+6
source share
1 answer

If you need up to 100 characters before and after, just change the regular expression from /\b($word)\b/i to /^.*?(.{0,100})\b($word)\b(.{0,100}).*?$/i

Then replace the replacement with \1<span class="highlight_word">\2</span>\3

And in general: $text = preg_replace("/^.*?(.{0,100})\b($word)\b(.{0,100}).*?$/i", '\1<span class="highlight_word">\2</span>\3', $text);

Edit: Updated after the comment on the poster. This should do what you want.

Edit2: regular expression will not work if there are no 100 characters on both sides. This one will work regardless of whether there are 100 characters before / after the word. If the number of characters is less than 100, it will match all of these.

Edit3: Updated response after comment on plan.

+8
source

Source: https://habr.com/ru/post/898645/


All Articles