【问题标题】:How to replace multiple %tags% in a string with PHP如何用 PHP 替换字符串中的多个 %tags%
【发布时间】:2010-07-03 19:49:35
【问题描述】:

在 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_replace,但我想知道是否有更好的方法来做到这一点。

谢谢。

【问题讨论】:

    标签: php string str-replace


    【解决方案1】:
    如果您知道要替换的占位符,

    str_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】:

      这个类应该这样做:

      <?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%');
      

      【讨论】:

      • 这似乎是一个很好的方法,并且更接近我想要的。我需要做一些基准测试,看看这与使用 str_replace() 函数相比如何。我感觉 str_replace() 会更快,但是这个类在实践中可能更容易使用。
      【解决方案3】:

      最简单和最短的选项是 preg_replace 与 '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】:

        来自 str_replace 的 PHP 手册:

        如果 searchreplace 是数组,那么 str_replace() 从每个取值 数组并使用它们进行搜索和 替换主题。如果更换有 比搜索少的值,然后是 空字符串用于其余的 替换值。如果搜索是 数组和替换是一个字符串,那么 此替换字符串用于 搜索的每个值。反过来 不过,这没有意义。

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

        【讨论】:

          猜你喜欢
          • 2017-12-02
          • 2017-12-10
          • 1970-01-01
          • 1970-01-01
          • 2011-09-01
          • 2020-08-31
          相关资源
          最近更新 更多