How to search for a substring found in a line of text and select it all

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:    // 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 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.

+3
source share
2 answers

HTML - , , angular. :

$pattern = "/[^<>]*$term[^<>]*/i";
$replace = "<span style=\"background: #f00\">$0</span>";
+2

preg_replace?

:

1: : strpos() stripos(), . : -X + L + Y, X Y - , , , L - . -tag .

2: : strpos/stripos. : , . : (strrpos/strripos) ' > ' 1 '<' 2. ;)

, , : " , ". -

-1

Source: https://habr.com/ru/post/1699598/


All Articles