php數(shù)組一對(duì)一替換實(shí)現(xiàn)代碼
更新時(shí)間:2012年08月31日 11:34:49 作者:
以下方法能實(shí)現(xiàn)匹配關(guān)鍵詞并分別對(duì)關(guān)鍵詞做特殊處理的功能,需要的朋友可以參考下
復(fù)制代碼 代碼如下:
<?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); //匹配所有關(guān)鍵詞
$search = explode(',','/'.implode('/,/',$matches[0]).'/');
//不存在匹配關(guān)鍵詞
if(empty($matches[0])) return false;
//特殊替換設(shè)置
$count = count($matches[0]);
foreach($replace as $key=>$val){
if(!isset($matches[0][$key])) unset($replace[$key]); //剔除越界替換
}
//合并特殊替換數(shù)組與匹配數(shù)組
for($i=0;$i<$count;$i++){
$matches[0][$i] = isset($replace[$i])? $replace[$i] : $matches[0][$i];
}
$replace = $matches[0];
//防止替換循環(huán),也就是替換字符仍是被替換字符,此時(shí)將其臨時(shí)替換一個(gè)特定字符$tmp_match
$replace = implode(',',$replace);
$replace = str_replace($word,$tmp_match,$replace); //臨時(shí)替換匹配字符
$replace = explode(',',$replace);
//替換處理
$string = preg_replace($search,$replace,$string,1); //每次只替換數(shù)組中的一個(gè)
$string = str_replace($tmp_match,$word,$string); //還原臨時(shí)替換的匹配字符
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);
/*
輸出結(jié)果:
原文:aaabaaacaaadaaa
輸出:aaabxxxcyyydaaa
原文:中文aaab中文ccaaad中文eee
輸出:中文aaab(替換中文2)ccaaad(替換中文3)eee
//*/
作者:Zjmainstay
您可能感興趣的文章:
- php數(shù)組函數(shù)序列之a(chǎn)rray_splice() - 在數(shù)組任意位置插入元素
- php數(shù)組函數(shù)序列之a(chǎn)rray_unshift() 在數(shù)組開(kāi)頭插入一個(gè)或多個(gè)元素
- PHP實(shí)現(xiàn)向關(guān)聯(lián)數(shù)組指定的Key之前插入元素的方法
- php實(shí)現(xiàn)插入數(shù)組但不影響原有順序的方法
- PHP刪除數(shù)組中的特定元素的代碼
- PHP從數(shù)組中刪除元素的四種方法實(shí)例
- PHP刪除數(shù)組中特定元素的兩種方法
- php中刪除數(shù)組的第一個(gè)元素和最后一個(gè)元素的函數(shù)
- php使用str_replace替換多維數(shù)組的實(shí)現(xiàn)方法分析
- PHP使用數(shù)組依次替換字符串中匹配項(xiàng)
- PHP實(shí)現(xiàn)數(shù)組向任意位置插入,刪除,替換數(shù)據(jù)操作示例
相關(guān)文章
php異常:Parse error: syntax error, unexpected T_ENCAPSED_AND_W
PHP會(huì)出現(xiàn)eval()'d code error 錯(cuò)誤提示的原因一般都是因?yàn)槟0邋e(cuò)誤,原因有以下幾種情況2011-05-05Zend Studio for Eclipse的java.lang.NullPointerException錯(cuò)誤的解決方
Zend Studio for Eclipse 6.x 可以算得上是最好的PHP的IDE了.2008-12-12在Mac上編譯安裝PHP7的開(kāi)發(fā)環(huán)境
這篇文章主要介紹了在Mac上編譯安裝PHP7的開(kāi)發(fā)環(huán)境的相關(guān)資料,需要的朋友可以參考下2015-07-07簡(jiǎn)單實(shí)現(xiàn)限定phpmyadmin訪問(wèn)ip的方法
如果你需要限定phpmyadmin特定的ip地址段進(jìn)行訪問(wèn),一個(gè)簡(jiǎn)單的方式可以在配置文件中進(jìn)行簡(jiǎn)單限定。2013-03-03Windows Server 2008 R2和2012中PHP連接MySQL過(guò)慢的解決方法
這篇文章主要介紹了Windows Server 2008 R2和2012中PHP連接MySQL過(guò)慢的解決方法,同時(shí)對(duì)Windows 7和8的本地開(kāi)發(fā)環(huán)境也有效,需要的朋友可以參考下2016-07-07用PHP將數(shù)據(jù)導(dǎo)入到Foxmail的實(shí)現(xiàn)代碼
下面的原理就是用PHP生成一個(gè)文件,然后下載并把這些資料導(dǎo)入他們的Foxmail地址簿中。2010-09-09