1

I have a little problem with the syntaxis for use preg_replace. I have a function that should replace in a .php file the values of many variables (like a config file).

Example:

file.php:

<?php
$var="string value";
?>

Function:

    function savedata($varname, $newvalue){
        $data = file_get_contents("file.php");
        $newdata = str_replace([find $varname="whatever";], $varname."=$newvalue;", $data);
        file_put_contents("file.php", $newdata);
    }

And if it runs should make the file to this:

<?php
$var="a new string value";
?>

I find

preg_replace('/"([^"]+)"/', $str, $content)

But works for only the quoted value and if i try add $varname.'='... at start, i get various errors.

Thanks for reading!

1 Answer 1

1

You can do the following which uses preg_quote() and preg_replace():

$data = '<?php
$var="string value";
?>'; # same as file_get_contents("file.php");

$varname = '$var';
$newvalue = 'a new string value';

$newdata = preg_replace('/('. preg_quote($varname) .'=")[^"]+(")/', "$1$newvalue$2", $data);

echo $newdata;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, when i tried with many variables the values got null, but with a little change in the remplace data "$1$newvalue$2" to $varname."=\"".$newvalue."\"" now it works perfectly, regards!

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.