如何使用 preg_replace 更改另一个 php/txt 文件中的变量名称和值

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

我对使用 preg_replace 的语法有一点疑问。我有一个函数应该在 .php 文件中替换许多变量的值(如配置文件)。

示例:

file.php:

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

函数:

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

如果它运行应该将文件制作成这样:

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

我发现

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

但仅适用于引用的值,如果我尝试添加 $varname.'='... 在开始时,我会遇到各种错误。

感谢阅读!

您可以使用 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) .'=")[^"]+(")/', "$newvalue", $data);

echo $newdata;