Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight search resuls with string part

i am using the code below to highlight the search results:

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

and its working fine.

But the preg_replace return the whole string and highlight the words that match.

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

A scenario is to get 100 chars before and 100 chars after the first match. Any help will be appreciated.

like image 782
ntan Avatar asked Oct 05 '11 05:10

ntan


People also ask

How do I highlight search results?

If you see a featured snippet, which is a search result found at the top of Google's organic results under the ads in a box, click it. After clicking on the snippet, Google will highlight text on the webpage that you saw in the featured snippet.

How do I highlight search results in HTML?

The <mark> HTML element is used to highlight text, so is the perfect element for this use case.

How do I highlight a portion of a text?

How to highlight text using your keyboard. To highlight with the keyboard, move to the starting location using the arrow keys. Then, hold down the Shift key, and press the arrow key in the direction you want to highlight. Once everything you want is highlighted, let go of the Shift key.

How do I highlight text in JavaScript search?

Highlight Text Using the Mark Tag Method in JavaScript If you surround any text inside the mark tag, the browser will automatically highlight it in a striking yellow color. This will make highlighting a searched text quite a simple task then.


1 Answers

If you want 100 characters before and after then just change your regex from/\b($word)\b/i to /^.*?(.{0,100})\b($word)\b(.{0,100}).*?$/i

Then change your replacement to \1<span class="highlight_word">\2</span>\3

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

Edit: Updated after poster comment. That should do what you want.

Edit2: The regex would fail if there weren't 100 characters on either side. This one will work regardless of whether there are 100 characters before/after the word now. If there are less than 100 characters it will match them all.

Edit3: Updated answer after poster comment.

like image 133
jmlsteele Avatar answered Sep 28 '22 10:09

jmlsteele