復制代碼 代碼如下:
<?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); //匹配所有關鍵詞
$search = explode(',','/'.implode('/,/',$matches[0]).'/');
//不存在匹配關鍵詞
if(empty($matches[0])) return false;
//特殊替換設置
$count = count($matches[0]);
foreach($replace as $key=>$val){
if(!isset($matches[0][$key])) unset($replace[$key]); //剔除越界替換
}
//合並特殊替換數組與匹配數組
for($i=0;$i<$count;$i++){
$matches[0][$i] = isset($replace[$i])? $replace[$i] : $matches[0][$i];
}
$replace = $matches[0];
//防止替換循環,也就是替換字符仍是被替換字符,此時將其臨時替換一個特定字符$tmp_match
$replace = implode(',',$replace);
$replace = str_replace($word,$tmp_match,$replace); //臨時替換匹配字符
$replace = explode(',',$replace);
//替換處理
$string = preg_replace($search,$replace,$string,1); //每次只替換數組中的一個
$string = str_replace($tmp_match,$word,$string); //還原臨時替換的匹配字符
return $string;
}
//示例1
$string = 'aaabaaacaaadaaa';
$word = 'aaa';
$replace = array(null,'xxx','yyy');
echo '原文:'.$string.'<br/>輸出:'.multiple_replace_words($word,$replace,$string).'<br/><br/>';
//示例2
$string = '中文aaab中文ccaaad中文eee';
$word = '中文';
$replace = array(null,'(替換中文2)','(替換中文3)');
echo '原文:'.$string.'<br/>輸出:'.multiple_replace_words($word,$replace,$string);
/*
輸出結果:
原文:aaabaaacaaadaaa
輸出:aaabxxxcyyydaaa
原文:中文aaab中文ccaaad中文eee
輸出:中文aaab(替換中文2)ccaaad(替換中文3)eee
//*/
作者:Zjmainstay