问题描述
我有一个电子邮件系统,用户可以在其中写一条消息,然后发送消息.我刚刚发现的主要问题,考虑这段代码
I have an email system, where user write a message and it will send the message. The main problem which I just found, consider this code
$findEmail = $this->Data->field('body', array('id' => 1610)); //$getUserEmailTemplate will take frm dbase and e.g: //Hi, @@MESSAGE@@. From: StackOverflow //It should change @@MESSAGE@@ part to data from $findEmail (in this example is the $74.97 ...) $getUserEmailTemplate = $findUser['User']['email_template']; $emailMessage = preg_replace('/B@@MESSAGE@@B/u', $findEmail, $getUserEmailTemplate); debug($findEmail); debug($emailMessage);
并为 $findemail 结果的电子邮件考虑此输入:
and consider this input for the email for $findemail result:
$74.97 $735.00s
$email 消息将导致:
$email Message will result in:
.97 5.00s
我该如何解决这个问题?我觉得我的 preg_replace 模式有问题.
How can I fix this? I feel like there's problem with my preg_replace pattern.
用户模板可以是任何东西,只要有@@MESSAGE@@,那部分就变成了用户消息输入.
User template can be anything, as long as there is @@MESSAGE@@ which, that part will be changed to the user message input.
谢谢
推荐答案
预解析替换文本以在后跟数字时转义 $(记住 $n> 在替换文本中使用时具有特殊含义).请参阅 php.net 文档页面上的评论:
Pre-parse the replacement text to escape the $ when followed by a number (remember that $n has special meaning when using in the replacement text). See the comment on the php.net docs page:
如果您的替换文本有可能包含任何字符串,例如$0.95",你需要避开那些 $n 反向引用:
If there's a chance your replacement text contains any strings such as "$0.95", you'll need to escape those $n backreferences:
<?php function escape_backreference($x){ return preg_replace('/$(d)/', '\$$1', $x); } ?>