php 查找替换

标签 php str-replace

这更像是一个“最佳实践”问题。

我有一些电子邮件模板,其中有几个我需要查找和替换的标签。

例如:

Dear [[customername]],
Blah blah blah blah, and more blah.

Your Invoice....
----------------------------------------------------------
Order Status: [[orderstatus]]
Order Number: [[orderid]]
Date Ordered: [[dateordered]]
Payment Method: [[paymentmethod]]
Billing Statement: [[billingstatement]]

无论如何,我在双括号内有几个这样的标签。 所以我使用一个简单的: $text = str_replace($oldWord , $newWord , $text);

我确信这是执行此操作的正常方法,但我只是好奇是否有人有不同的想法。否则,我会坚持我正在做的事情。

最佳答案

您可以将数组与 str_replace 一起使用:

$oldWords = array('[[customername]]',
                  '[[orderstatus]]'
                 );
$newWords = array($customerName,
                  $orderStatus
                 );

$newText = str_replace($oldWords , $newWords , $text); 

您还可以将 preg_replace 与数组一起使用

$oldWords = array('/\[\[customername\]\]/',
                  '/\[\[orderstatus\]\]/'
                 );
$newWords = array($customerName,
                  $orderStatus
                 );

$newText = preg_replace($oldWords , $newWords , $text); 

关于php 查找替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4994643/

相关文章:

c - 实现 "\\"而不是 ""(空格)

Ruby - 如果实例不匹配,则替换字符串中的单词

PHP-如果 href 或 src 不以 http、https 或 www 开头,则删除特定标记或 img 标记

php - 由于 SSL,无法检查站点是启动还是关闭

php异常额外参数

php - 如何在 str_replace() 的搜索参数中获取数组中的数值以按照我期望的方式进行映射?

Javascript String.replace() ,结果不明确

php - 在邮件正文 phpmailer 类中添加嵌入图像

php - 使用 PHP 和 MySQL 执行 SQL 查询以按关键字搜索结果时出错

java - 用另一个流中的字符串替换一个流中的字符串