首頁  >  文章  >  後端開發  >  php數組一對一替換實現代碼

php數組一對一替換實現代碼

高洛峰
高洛峰原創
2016-12-01 10:28:16925瀏覽

複製程式碼 程式碼如下: 
header("Content-type: text/html; charset=utf-8"); 
function multiple_replace_words($word,$replace,$string,$t. '){ 
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$matches[0][$i] = isset($replace[$i ])? $replace[$i] : $matches[0][$i]; 

$replace = $matches[0]; 
//防止替換循環,也就是替換字符仍是被替換字符,此時將其暫時替換一個特定字元$tmp_match 
$replace = implode(',',$replace); 
$replace = str_replace($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'; re
$word = 'aaa'; (null,'xxx','yyy'); 
echo '原文:'.$string.'
輸出:'.multiple_replace_words($word,$replace,$string).'

'; 
//例2 
$string = '中文aaab中文ccaaad中文eee'; 
$word = '中文'; 
$replace = array(null,'(替換中文2)','(取代中文2)','(代入中文3)'); 
echo '原文:'.$string.'
輸出:'.multiple_replace_words($word,$replace,$string); 
/* 
輸出結果: 
aaabaaabaaacaaadao🠟帶輸出: aaabxxxcyyydaaa 
原文:中文aaab中文ccaaad中文eee 
輸出:中文aaab(替換中文2)ccaaad(替換中文3)eee 
//*/ 

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn