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

标签 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;

等..

我知道我可以在一个字符串上多次运行 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/

相关文章:

php - MYSQL选择至少包含另一个表中的两个元素的类别

php - 使用 PDO 时为 "Notice: Undefined variable: db"

Javascript 等同于 Ruby 的单引号?

javascript - 添加包含数字的javascript变量时如何防止链

c++ - 如何查找和替换字符串中所有出现的子字符串?

javascript - 替换第 n 次出现的 javascript

php - 在多对多关系的情况下如何插入数据透视表? (拉拉维尔 5.3)

php - 在symfony中获取插入行的主键id

java - 字符串数组无法在索引[0]上分配

python - 使用 str.replace 在循环中运行 XOR 加密不会更改某些字符