I am trying to highlight search results, but I want to include surrounding text, which is limited by the attached tags.
So, if $ term is "cool", preg_replace should end:
<div><span style="background: #f00">My hair cut so cool!</span></div>
Unfortunately, my regex does not seem to capture the surrounding text, but only $ term. The surrounding tags can be any valid tag.
0:
1: $term = 'cool';
2: ob_start();
3:
10: foreach($items as $item) {
11:
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 in a separate class. Because of this, I cannot perform a replacement in the loop itself. In addition, it is more efficient to process the final output instead of each cycle over the data.
Robert F
source
share