0

I have a file that i'm parsing And I'm trying to replace $mail["email_from"] = "[email protected]"; with $mail["email_from"] = request("email");,(meaning that I want to replace all the lines that has $mail["email_from"] at the begining an ; at the end) and here's my preg_replace:

$email = "$mail[\"email_from\"] = request(\"email\")";
$newcontent = preg_replace("/\$mail[\"email_from\"](.+);/",$email,$content); 

What's the error in my code? and how to fix it? Much appreciated

DEMO

2
  • does that make sense? Commented Jun 13, 2014 at 15:51
  • 2
    "$mail" is interpreted because you're using double-quotes. Use simple quote instead Commented Jun 13, 2014 at 15:51

3 Answers 3

1

After using good quotes and escaping all chars you need, this works:

$email = '$mail["email_from"] = "[email protected]";';
$replacement = '$mail["email_from"] = request("email");';
$newContent = preg_replace('/\\$mail\\[\\"email_from\\"\\](.+);/i', $replacement, $email); 
echo $newContent; //$mail["email_from"] = request("email");
Sign up to request clarification or add additional context in comments.

4 Comments

Could you please check the demo !
And could you please try my answer? It works as expected. See it there: 3v4l.org/uDC6E#v5425
I might be completely wrong in asking, but why would you wanna print that text?
@PrashantBalan I don't even know neither but maybe to store it in a PHP file and using it later I guess
1
$email = "$mail[\"email_from\"] = request(\"email\")";
         ^---double-quoted string
          ^^^^^---array reference

You probably need

$email = "\$mail[\"email_from\"] = request(\"email\")";
          ^--escape the $

2 Comments

I tried that I think it got to do also with the regex ! here's a demo :codepad.org/26XkxWZJ
you're going overboard with regexes. this could be done MUCh easier with a simple str_replace() than with a regex.
1

Use ^ and $ to specify beginning and end of line. Special characters like $, [, and ] need to be escaped.

<?php
$content = '$mail["email_from"] = "[email protected]";';
$email = '$mail["email_from"] = request("email");';
$newcontent = preg_replace('/^\$mail\["email_from"\] =.+;$/',$email,$content); 

echo $newcontent . "\n";

outputs:

$mail["email_from"] = request("email");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.