REGEX search only affecting last occurence in preg_replace function in PHP error

46 Views Asked by At

I have a function highlighting word for a glossary. I created a regex to replace occurrence of word that are preceded and followed by word starting/ending characters like spaces, commas, HTML tags, etc. It also incorporate plurals and 'féminin' version of the word (french is a complicated language) in glossary in the highlight (the [esx]{0,2} part). The \x{00A0} stands for   because it is intended to work in HTML text too.

It all works fine except I realized it only change the last occurrence of the word in the targeted text. Any idea how to correct that ?

My simplified version of the function for analysis :

function highlight_word ($word, $content) {

     $search = "#(.*)([\s\x{00A0} ,\.-;\(\)\">])(" . $part . ")([esx]{0,2})([,\.;<\"-\)\(]{0,1}[\s\x{00A0} ,\.;\"-\)\(<])(.*)#i";
     $content = preg_replace( $search, '\1\2<strong>\3\4</strong>\5\6', $content );

     return $content;

}

Thanks!!!!

It took a while before I realised that only last occurrence was replaced. I initially though it was not discovering some words, but its because these word occurred later in string. The last occurrence being correctly highlighted.

I though preg_replace was replacing all occurrences. Should I use some kind of preg_replace_callback() ??

0

There are 0 best solutions below