Preg_replace causing the removal of dollar signs

I have a mail system where the user writes a message and he sends a message. The main problem I just found, consider this code

$findEmail = $this->Data->field('body', array('id' => 1610)); //$getUserEmailTemplate will take frm dbase and eg: //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 message for the result of $ findemail:

 $74.97 $735.00s 

$ email A message will result in:

 .97 5.00s 

How can i fix this? I feel the problem is with my preg_replace template.

The user template can be any, if there is @@ MESSAGE @@, which will be changed to the user's input.

thanks

+7
string php regex preg-replace cakephp
source share
4 answers

Examine the replacement text first to avoid $ , followed by a number (remember that $n is of particular importance when used in the replacement text). See the comment on the php.net docs page:

If there is a chance that your replacement text contains any lines, such as "$ 0.95", you will need to avoid these $ n backlinks:

 <?php function escape_backreference($x){ return preg_replace('/\$(\d)/', '\\\$$1', $x); } ?> 
+12
source share

If (ever) the template was in $getUserEmailTemplate , you $getUserEmailTemplate (destroyed) this line,

 $getUserEmailTemplate = "@@ MESSAGE@ @"; 

So just delete this line and make sure that $getUserEmailTemplate really contains anything and the best template.

0
source share

That's why:

A portion of the text $1 replacement text indicates the first group / match found. Therefore, if you have abc 123 and you try preg_match('/([\w]+)-([\d]+)/') , the regular expression will store inside something like $1 = abc and $2 = 123 . These variables will exist even if they do not matter.

So for example:

 $text = '[shortcode]'; $replacement = ' some $var $101 text'; $result = preg_replace('/\[shortcode\]/', $var, $text); // returns "some $var 1 text" 

Since the match group $10 empty, it will be replaced by an empty string.

To run the preg_replace function preg_replace to remove the text $NN from your REPLACE text.

Happy coding.

0
source share

Guess that your template contains only pure PHP and is trying to use the $ 74 as variable, which does not exist and does not contain any data. Therefore, change the quotation marks in the pattern to single quotes ' .

guessed pattern:

 $tpl = "Sum: $74.97"; //results in "Sum: .97" 

fixed template:

 $tpl = 'Sum: $74.97'; //results in "Sum: $74.97" 
-one
source share

All Articles