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.
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.
The <mark> HTML element is used to highlight text, so is the perfect element for this use case.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With