色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

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

復制代碼 代碼如下:
<?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

php技術php數組一對一替換實現代碼,轉載需保留來源!

鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。

主站蜘蛛池模板: 子长县| 金沙县| 昆山市| 瑞安市| 白城市| 永寿县| 西畴县| 仁寿县| 梅州市| 江口县| 呈贡县| 芒康县| 商丘市| 胶州市| 政和县| 泗水县| 昌吉市| 绵竹市| 西城区| 营山县| 黄陵县| 武威市| 白城市| 吉水县| 纳雍县| 宜川县| 阿图什市| 乐清市| 吴江市| 共和县| 突泉县| 锡林郭勒盟| 汕尾市| 永安市| 泊头市| 托克逊县| 鹿邑县| 恩平市| 县级市| 石林| 雅江县|