Copy code The code is as follows:
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]).'/');
// There is no matching keyword
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 out-of-bounds replacement
}
//Merge the special replacement array and the matching array
for($i=0;$i<$count;$i++){
$matches[0][$i] = isset($replace[ $i])? $replace[$i] : $matches[0][$i];
}
$replace = $matches[0];
//Prevent replacement loops, that is, replacement The character is still the replaced character, and now it is temporarily replaced with a specific character $tmp_match
$replace = implode(',',$replace);
$replace = str_replace($word,$tmp_match,$replace ); //Temporary replacement of matching characters
$replace = explode(',',$replace);
//Replacement processing
$string = preg_replace($search,$replace,$string,1) ; //Replace only one character in the array at a time
$string = str_replace($tmp_match,$word,$string); //Restore the temporarily replaced matching character
return $string;
}
//Example 1
$string = 'aaabaaacaaadaaa';
$word = 'aaa';
$replace = array(null,'xxx','yyy');
echo 'Original text :'.$string.'
Output: '.multiple_replace_words($word,$replace,$string).'
';
//Example 2
$string = 'Chinese aaab Chinese ccaaad Chinese eee';
$word = 'Chinese';
$replace = array(null,' (replace Chinese 2)',' (replace Chinese 3) ');
echo 'Original text: '.$string.'
Output: '.multiple_replace_words($word,$replace,$string);
/*
Output result:
Original text: aaabaaacaaadaaa
Output: aaabxxxcyyydaaa
Original text: Chinese aaab Chinese ccaaad Chinese eee
Output: Chinese aaab (replace Chinese 2) ccaaad (replace Chinese 3) eee
//*/
Author: Zjmainstay
http://www.bkjia.com/PHPjc/325899.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325899.htmlTechArticleCopy the 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('/'.$wo...