Preg_replace with array replacements

前端 未结 4 1202
说谎
说谎 2020-12-03 07:50
$string = \":abc and :def have apples.\";
$replacements = array(\'Mary\', \'Jane\');

should become:

Mary and Jane have apples.
         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 08:31

    For a Multiple and Full array replacement by Associative Key you can use this to match your regex pattern:

       $words=array("_saudation_"=>"Hello", "_animal_"=>"cat", "_animal_sound_"=>"MEooow");
       $source=" _saudation_! My Animal is a _animal_ and it says _animal_sound_ ... _animal_sound_ ,  _no_match_";
    
    
      function translate_arrays($source,$words){
        return (preg_replace_callback("/\b_(\w*)_\b/u", function($match) use ($words) {    if(isset($words[$match[0]])){ return ($words[$match[0]]); }else{ return($match[0]); } },  $source));
      }
    
    
        echo translate_arrays($source,$words);
        //returns:  Hello! My Animal is a cat and it says MEooow ... MEooow ,  _no_match_
    

    *Notice, thats although "_no_match_" lacks translation, it will match during regex, but preserve its key. And keys can repeat many times.

提交回复
热议问题