Tips:点此可运行HTML源码

php数组一对一替换

 以下方法能实现匹配关键词并分别对关键词做特殊处理的功能。

 1 <?php
 2     header("Content-type: text/html; charset=utf-8"); 
 3     
 4     function multiple_replace_words($word,$replace,$string,$tmp_match='#a_a#'){
 5         preg_match_all('/'.$word.'/',$string,$matches);    //匹配所有关键词
 6         $search = explode(',','/'.implode('/,/',$matches[0]).'/');        
 7         //不存在匹配关键词
 8         if(empty($matches[0])) return false;
 9         
10         //特殊替换设置
11         $count = count($matches[0]);
12         foreach($replace as $key=>$val){
13             if(!isset($matches[0][$key])) unset($replace[$key]);    //剔除越界替换
14         }
15 
16         //合并特殊替换数组与匹配数组
17         for($i=0;$i<$count;$i++){
18             $matches[0][$i] = isset($replace[$i])? $replace[$i] : $matches[0][$i];
19         }
20         $replace = $matches[0];
21         
22         //防止替换循环,也就是替换字符仍是被替换字符,此时将其临时替换一个特定字符$tmp_match
23         $replace = implode(',',$replace);
24         $replace = str_replace($word,$tmp_match,$replace);    //临时替换匹配字符
25         $replace = explode(',',$replace);
26         
27         
28         //替换处理
29         $string = preg_replace($search,$replace,$string,1);                    //每次只替换数组中的一个
30         $string = str_replace($tmp_match,$word,$string);        //还原临时替换的匹配字符
31         
32         return $string;
33     }
34     
35     //示例1
36     $string = 'aaabaaacaaadaaa';    
37     $word = 'aaa';
38     $replace = array(null,'xxx','yyy');
39     echo '原文:'.$string.'<br/>输出:'.multiple_replace_words($word,$replace,$string).'<br/><br/>';
40     
41     //示例2
42     $string = '中文aaab中文ccaaad中文eee';    
43     $word = '中文';
44     $replace = array(null,'(替换中文2)','(替换中文3)');
45     echo '原文:'.$string.'<br/>输出:'.multiple_replace_words($word,$replace,$string);
46     
47     /*
48         输出结果:
49         原文:aaabaaacaaadaaa
50         输出:aaabxxxcyyydaaa
51         
52         原文:中文aaab中文ccaaad中文eee
53         输出:中文aaab(替换中文2)ccaaad(替换中文3)eee
54     //*/
posted @ 2012-08-30 19:06  Zjmainstay  阅读(2307)  评论(0编辑  收藏  举报