i am using the code below to highlight the search results:
$text = preg_replace("/\b($word)\b开发者_如何学Python/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 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.
精彩评论