Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

php - preg_replace causing dollar signs get removed

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

and consider this input for the email for $findemail result:

$74.97
$735.00s

$email Message will result in:

.97
5.00s

How can I fix this? I feel like there's problem with my preg_replace pattern.

User template can be anything, as long as there is @@MESSAGE@@ which, that part will be changed to the user message input.

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...