Vega
Vega

Reputation: 59

How to use preg_replace for change variable names and values in another php/txt file

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!

Upvotes: 1

Views: 446

Answers (1)

Grokify
Grokify

Reputation: 16334

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;

Upvotes: 1

Related Questions