php array one to one substitution implementation code
- 2020-05-19 04:25:11
- OfStack
<?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 substitution Settings
$count = count($matches[0]);
foreach($replace as $key=>$val){
if(!isset($matches[0][$key])) unset($replace[$key]); // Eliminate out of bounds substitutions
}
// Merges a special substitution array with a matching array
for($i=0;$i<$count;$i++){
$matches[0][$i] = isset($replace[$i])? $replace[$i] : $matches[0][$i];
}
$replace = $matches[0];
// To prevent a replacement loop, where the replacement character is still the replaced character, temporarily replace it 1 Particular characters $tmp_match
$replace = implode(',',$replace);
$replace = str_replace($word,$tmp_match,$replace); // Temporary replacement of matching characters
$replace = explode(',',$replace);
// Replace the processing
$string = preg_replace($search,$replace,$string,1); // You just replace the array at a time 1 a
$string = str_replace($tmp_match,$word,$string); // Restores the matching character of the temporary replacement
return $string;
}
// The sample 1
$string = 'aaabaaacaaadaaa';
$word = 'aaa';
$replace = array(null,'xxx','yyy');
echo ' The original: '.$string.'<br/> Output: '.multiple_replace_words($word,$replace,$string).'<br/><br/>';
// The sample 2
$string = ' Chinese aaab Chinese ccaaad Chinese eee';
$word = ' Chinese ';
$replace = array(null,' (substitute Chinese 2 ) ',' (substitute Chinese 3 ) ');
echo ' The original: '.$string.'<br/> Output: '.multiple_replace_words($word,$replace,$string);
/*
Output results:
The original: aaabaaacaaadaaa
Output: aaabxxxcyyydaaa
Original text: Chinese aaab Chinese ccaaad Chinese eee
Output: Chinese aaab (substitute Chinese 2 ) ccaaad (substitute Chinese 3 ) eee
//*/
Author: Zjmainstay