国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > PHP > 正文

php數(shù)組一對一替換實現(xiàn)代碼

2024-05-04 23:14:12
字體:
來源:轉載
供稿:網(wǎng)友

復制代碼 代碼如下:


<?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]); //剔除越界替換
}
//合并特殊替換數(shù)組與匹配數(shù)組
for($i=0;$i<$count;$i++){
$matches[0][$i] = isset($replace[$i])? $replace[$i] : $matches[0][$i];
}
$replace = $matches[0];
//防止替換循環(huán),也就是替換字符仍是被替換字符,此時將其臨時替換一個特定字符$tmp_match
$replace = implode(',',$replace);
$replace = str_replace($word,$tmp_match,$replace); //臨時替換匹配字符
$replace = explode(',',$replace);
//替換處理
$string = preg_replace($search,$replace,$string,1); //每次只替換數(shù)組中的一個
$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
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 巴彦淖尔市| 长兴县| 巫溪县| 巴南区| 镇康县| 贺兰县| 全南县| 温宿县| 黄冈市| 牟定县| 蒲江县| 广宗县| 叶城县| 吉隆县| 社会| 龙岩市| 育儿| 白水县| 柞水县| 南召县| 普安县| 喜德县| 蒙城县| 巴马| 莱西市| 盐边县| 扶绥县| 福建省| 襄汾县| 阿鲁科尔沁旗| 枝江市| 湘潭县| 南平市| 贵南县| 长顺县| 新乡县| 凤台县| 增城市| 肥城市| 桐城市| 两当县|