替换 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,但我想知道是否有更好的方法。
谢谢。
最佳答案
如果您知道要替换的占位符,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 - 如何用 PHP 替换字符串中的多个 %tags%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3172689/