I'm trying to highlight the search results but I want to include the surrounding text that is limited by the enclosing tags.
So if the $term is "cool" the preg_replace should end up with:
<div><span style="background: #f00">My hair cut so cool!</span></div>
Unfortunately my regex doesn't seem to capture the surrounding text, only the $term. The surrounding tags could be any kind of valid tag.
0:
1: $term = 'cool';
2: ob_start();
3:
10: foreach($items as $item) {
11: // echoing results here
12: echo '<div>' . $item->text . '</div>';
13: }
30: $content = ob_get_contents();
31: ob_clean() ;
32:
33: $pattern = "/(?<!<[^>])($term)/i";
34: $replace = "<span style=\"background: #f00\">$1</span>";
35: echo preg_replace($pattern, $replace, $content);
36:
EDIT: The foreach loop is one of many and is located in a separate class. Because of this I can't do the replacement in the loop itself. Also it seems more efficient to process the final output instead of each loop over the data.