Copy Code code as follows:
<?php
Header ("content-type:text/html; Charset=utf-8 ");
function Multiple_replace_words ($word, $replace, $string, $tmp _match= ' #a_a # ') {
Preg_match_all ('/'. $word. /', $string, $matches); Match all Keywords
$search = Explode (', ', '/'. Implode ('/,/', $matches [0]). ' /');
No matching keywords exist
if (empty ($matches [0])) return false;
Special Replacement settings
$count = count ($matches [0]);
foreach ($replace as $key => $val) {
if (!isset ($matches [0][$key])) unset ($replace [$key]); Eliminate cross-border replacements
}
Merging special substitution arrays with matching arrays
for ($i =0; $i < $count; $i + +) {
$matches [0][$i] = isset ($replace [$i])? $replace [$i]: $matches [0][$i];
}
$replace = $matches [0];
Prevents the substitution loop, which is that the replacement character is still a substituted character, and temporarily replaces it with a specific character $tmp_match
$replace = Implode (', ', $replace);
$replace = Str_replace ($word, $tmp _match, $replace); Temporary substitution of matching characters
$replace = Explode (', ', $replace);
Replace processing
$string = Preg_replace ($search, $replace, $string, 1); Replace only one of the arrays at a time
$string = Str_replace ($tmp _match, $word, $string); Restore a temporary replacement match character
return $string;
}
Example 1
$string = ' aaabaaacaaadaaa ';
$word = ' AAA ';
$replace = Array (null, ' xxx ', ' yyy ');
Echo ' original: '. $string. ' <br/> output: '. Multiple_replace_words ($word, $replace, $string). ' <br/><br/> ';
Example 2
$string = ' Chinese aaab Chinese ccaaad Chinese eee ';
$word = ' Chinese ';
$replace = Array (null, ' (replace Chinese 2) ', ' (replace Chinese 3) ');
Echo ' original: '. $string. ' <br/> output: '. Multiple_replace_words ($word, $replace, $string);
/*
Output results:
Original: AAABAAACAAADAAA
Output: AAABXXXCYYYDAAA
Original: Chinese Aaab Chinese ccaaad Chinese eee
Output: Chinese Aaab (replace Chinese 2) Ccaaad (replace Chinese 3) Eee
//*/
Author: Zjmainstay