php数组一对一替换实现代码

yipeiwu_com5年前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实现基于回溯法求解迷宫问题的方法。分享给大家供大家参考,具体如下: 引言 最近在leetcode上看了些算法题,有些看着很简单的很常用的东西,竟然一下子想不出来怎么求...

PHP实现的MD5结合RSA签名算法实例

本文实例讲述了PHP实现的MD5结合RSA签名算法。分享给大家供大家参考,具体如下: <?php class Md5RSA{ /** * 利用约定数据和私钥生...

Http 1.1 Etag 与 Last-Modified提高php效率

Http 1.1 Etag 与 Last-Modified提高php效率

在 Blog 盛行的今天,一些 Web 应用需要解析大量的 RSS Feed .如何提高效率是个非常重要的问题.在 MagpieRSS 的 Features 中列举了这样的一条: HT...

PHP生成数组再传给js的方法

<script type="text/javascript"> var slist = '<?php echo urlencode(json_encod...

php几个预定义变量$_SERVER用法小结

本文实例总结了php几个预定义变量$_SERVER的用法。分享给大家供大家参考。具体如下: 复制代码 代码如下:<?php echo 'documentroot:'.$_S...