Home > Backend Development > PHP Tutorial > PHP array one-to-one replacement implementation code

PHP array one-to-one replacement implementation code

高洛峰
Release: 2023-03-02 16:44:01
Original
986 people have browsed it

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 substitutions
}
//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, the replacement character is still the replaced character , at this time, temporarily replace it with a specific character $tmp_match
$replace = implode(',',$replace);
$replace = str_replace($word,$tmp_match,$replace); //Temporarily replace the matching character
$ replace = explode(',',$replace);
//Replacement processing
$string = preg_replace($search,$replace,$string,1); //Only replace one element in the array at a time
$string = str_replace ($tmp_match,$word,$string); //Restore the temporarily replaced matching characters
return $string;
}
//Example 1
$string = 'aaabaaacaaadaaa';
$word = 'aaa';
$replace = array(null,'xxx','yyy');
echo 'Original text:'.$string.'
Output:'.multiple_replace_words($word,$replace,$string).'< br/>
';
//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
//*/

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template