preg_replace导致美元符号被删除

Har*_*rts 7 php regex string cakephp preg-replace

我有一个电子邮件系统,用户在那里写一条消息并发送消息.我刚发现的主要问题是考虑这个代码

    $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);
Run Code Online (Sandbox Code Playgroud)

并考虑$ findemail结果的电子邮件的此输入:

$74.97
$735.00s
Run Code Online (Sandbox Code Playgroud)

$ email消息将导致:

.97
5.00s
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?我觉得我的preg_replace模式存在问题.

用户模板可以是任何东西,只要有@@ MESSAGE @@,该部分将被更改为用户消息输入.

谢谢

Bra*_*tie 12

预解析替换文本以逃避$后跟数字的时间(记住$n在替换文本中使用时具有特殊含义).请参阅php.net文档页面上的评论:

如果您的替换文本有可能包含任何字符串,例如"$ 0.95",那么您将需要逃避那些$ n反向引用:

<?php
  function escape_backreference($x){
    return preg_replace('/\$(\d)/', '\\\$$1', $x);
  }
?>
Run Code Online (Sandbox Code Playgroud)

  • 它不会杀死_all_```,只有`$`后跟一个介于0到99之间的数字(最大反向引用数),因为没有这样的子模式,它会替换空字符串.一个简单的`addcslashes($ replacestring,'$');`将会处理它. (3认同)
  • @djot:[不这么认为?](http://sandbox.onlinephpfunctions.com/code/f81db648bffbb7e658de2d8c0ea47fef59a685af)(以及[清理版](http://sandbox.onlinephpfunctions.com/code/c666c40dfd7de78b5431fff1f3b253cdf51cbe89)) (2认同)

djo*_*jot -1

猜测您的模板仅包含“纯”PHP 并尝试使用 $74 作为变量,该变量不存在且不包含任何数据。因此将模板中的引号更改为单引号'

猜测模板:

$tpl = "Sum: $74.97"; //results in "Sum: .97"
Run Code Online (Sandbox Code Playgroud)

更正后的模板:

$tpl = 'Sum: $74.97'; //results in "Sum: $74.97"
Run Code Online (Sandbox Code Playgroud)