代码之家  ›  专栏  ›  技术社区  ›  Andy

如何用PHP替换字符串中的多个%tags%

  •  3
  • Andy  · 技术社区  · 16 年前

    替换PHP字符串中一组短标记的最佳方法是什么,例如:

    $return = "Hello %name%, thank you for your interest in the %product_name%.  %representative_name% will contact you shortly!";
    

    其中,我将定义%name%是某个字符串,来自数组或对象,例如:

    $object->name;
    $object->product_name;
    

    等。。

    我知道我可以在一个字符串上运行str\u replace多次,但我想知道是否有更好的方法来实现这一点。

    谢谢。

    4 回复  |  直到 16 年前
        1
  •  14
  •   Jon Cram    16 年前

    如果您知道要替换的占位符,str\u replace()似乎是一个理想的选择。这只需要运行一次,而不是多次。

    $input = "Hello %name%, thank you for your interest in the %product_name%.  %representative_name% will contact you shortly!";
    
    $output = str_replace(
        array('%name%', '%product_name%', '%representative_name%'),
        array($name, $productName, $representativeName),
        $input
    );
    
        2
  •  2
  •   codez    16 年前

    这门课应该做到:

    <?php
    class MyReplacer{
      function __construct($arr=array()){
        $this->arr=$arr;
      }
    
      private function replaceCallback($m){
        return isset($this->arr[$m[1]])?$this->arr[$m[1]]:'';
      }
    
      function get($s){  
        return preg_replace_callback('/%(.*?)%/',array(&$this,'replaceCallback'),$s);
      }
    
    }
    
    
    $rep= new MyReplacer(array(
        "name"=>"john",
        "age"=>"25"
      ));
    $rep->arr['more']='!!!!!';  
    echo $rep->get('Hello, %name%(%age%) %notset% %more%');
    
        3
  •  2
  •   user187291    16 年前

    最简单和最短的选择是pregèu替换为“e”开关

    $obj = (object) array(
        'foo' => 'FOO',
        'bar' => 'BAR',
        'baz' => 'BAZ',
    );
    
    $str = "Hello %foo% and %bar% and %baz%";
    echo preg_replace('~%(\w+)%~e', '$obj->$1', $str);
    
        4
  •  1
  •   erjiang    16 年前

    从str\u的PHP手册中替换:

    搜索 那么是数组吗 str\u replace() 从每个 数组并使用它们进行搜索和 主题 . 如果更换有 值比搜索少,然后 空字符串用于 替换值。如果搜索是 此替换字符串用于 搜索的每一个价值。诡谋 不过,这没有道理。

    http://php.net/manual/en/function.str-replace.php