We have the following test code.

$subject = "Мама мыла раму, дочь чертила пентаграмму"; $array = array( 'Мама', 'Мама мыла', 'Мама мыла раму', 'Мама мыла раму, дочь', 'Мама мыла раму, дочь чертила', ); $array_pattern = array(); foreach ($array as $value) { $array_pattern[] = "#^{$value}#i"; } $result = preg_replace($array_pattern, '', $subject); echo $result; 

As a result, we get a string of soap frame, the daughter drew a pentagram instead of the desired string pentagram . How to change the behavior of preg_replace in this case?

PS The question is related to this topic .

  • You can sort the source array by descending length) - vp_arth
  • Actually, I did not help it ... - Dmitry Gvozd
  • Strange with this code really sorting helps. - Dmitry Gvozd

1 answer 1

You can sort the source array in descending order of length:

 <?php $subject = "Мама мыла раму, дочь чертила пентаграмму"; $array = array( 'Мама', 'Мама мыла', 'Мама мыла раму', 'Мама мыла раму, дочь', 'Мама мыла раму, дочь чертила', ); usort($array, function($a, $b){return strlen($b) - strlen($a);}); $array_pattern = array(); foreach ($array as $value) { $array_pattern[] = "#^{$value}#i"; } $result = preg_replace($array_pattern, '', $subject); echo $result; // ' пентаграмму' 

Feeddle