如何用PHP替换字符串中的多个%tags%
替换PHP字符串中的一组短标记的最佳方法是什么,例如:如何用PHP替换字符串中的多个%tags%,php,string,str-replace,Php,String,Str Replace,替换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; 等等 我知道我可以在一个字符串上多
$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 str_replace手册: 如果搜索和替换是数组,则 str_replace()从每个 数组,并使用它们进行搜索和 根据主题替换。如果更换有 值少于搜索,然后是 空字符串用于剩余的 替换值。如果搜索是一个 数组和替换为字符串,则 此替换字符串用于 搜索的每一个价值。诡谋 不过,这毫无意义 如果您知道要替换的占位符,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
);
这门课应该做到:
<?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%');
最简单和最短的选项是preg_替换为“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);
这似乎是一个很好的方法,而且更接近我想要的。我需要做一些基准测试,看看这与使用str_replace()函数相比如何。我感觉str_replace()会更快,但是这个类在实践中可能更容易使用。