preg_replace导致美元符号被删除 [英] preg_replace causing dollar signs get removed

查看:103
本文介绍了preg_replace导致美元符号被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个电子邮件系统,其中用户写一条消息,它将发送消息。
我刚刚发现的主要问题,考虑这个代码

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 docs页面上的评论

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反向引用: p>

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);
  }
?>

这篇关于preg_replace导致美元符号被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆