如何使用PHP替换字符串中的多个%标签%

3

如何在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,但我想知道是否有更好的方法。

谢谢。

4个回答

14

如果您知道要替换的占位符,那么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()会更快,但在实践中使用这个类可能更容易。 - Andy

2
最简单和最短的选择是使用带有'e'开关的preg_replace函数。
$obj = (object) array(
    'foo' => 'FOO',
    'bar' => 'BAR',
    'baz' => 'BAZ',
);

$str = "Hello %foo% and %bar% and %baz%";
echo preg_replace('~%(\w+)%~e', '$obj->$1', $str);

1

从PHP手册中关于str_replace的描述:

如果 searchreplace 都是数组,那么 str_replace() 会从每个数组中取出一个值,并用它们来搜索和替换 subject。如果 replace 比 search 少,则其余的替换值将使用空字符串。如果 search 是一个数组而 replace 是一个字符串,则该替换字符串将用于 search 的每个值。反之则没有意义。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接