zoukankan      html  css  js  c++  java
  • 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     //*/
    作者:Zjmainstay
             
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    版权信息
  • 相关阅读:
    入门级科普 | ICO→STO→IEO,下一个会是IDO吗?
    去中心化金融(DeFi):一个新的金融科技革命
    kubernetes docker 查看站点访问权限问题
    Pycharm 插件中的git使用
    Selenium 中对于table的判断
    macOS 终端打开提示:zsh compinit: insecure directories
    Mac 删除开机选项
    pytest-BDD 的学习
    Gherkin学习笔记
    Cucumber入门之Gherkin
  • 原文地址:https://www.cnblogs.com/Zjmainstay/p/php_multiple_replace_words.html
Copyright © 2011-2022 走看看