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.
source share