I'm having a problem figuring out how to prevent preg_replace() from
replacing substrings when one element of the pattern array matches a
portion of a string that would match a subsequent value in the pattern
array.
Say I have an two arrays:
find => Array
(
[0] => 'fred'
[1] => 'tom'
[2] => 'frederick'
)
replace => Array
(
[0] => 'person1'
[1] => 'person2'
[2] => 'person3'
)
and a string $string = 'fred knows tom who knows frederick'. So the
string contains an instance of each $find value, and I'd like to replace
each one with its corresponding $replace value.
The problem is that preg_replace() changes 'frederick' to 'person1erick'
before even getting to find[2] ('frederick'), which at this point won't
find anything to replace, and I'm left with 'person1 knows person2 who
knows person1erick' when what I want to end up with is 'person1 knows
person2 knows person3.'
Also, the actual values in the $find array are not names but strings
representing each unique combination of HTML tags in $string (such as
'<br>', '<b>', '<br><u>', so that the <u> here would be left over
unmatched). It seems to me that my only option is to write a function to
sort $find in reverse order by length, so that the longer strings are
replaced first. Or am I missing something obvious?
Thanks in advance,
Andy