preg_replace() 不起作用

preg_replace() doesn't work

我目前正在尝试更改配置文件中的变量。我试过以下方法:

public static function change(){
    $fl = file("../config.inc.php");
    $key = $_POST['key'];
    $id = $_POST['id'];
    $secret = $_POST['secret'];
    $content = "";
    foreach($fl as $line){
        $content .= $line;
    }
    $content = preg_replace("$licence = array\(\'key\'=>\'(.*?)\'\);$", "licence = array('key'=>'$key');", $content);

    $content = preg_replace("/$rey_connect = array\((.*?\'client_id\'=>\')(.*?)('.*?\'client_secret\'=>\')(.*?)(\')(.*?)(?:\));(?:\n|$)/", "$rey_connect = array($id$secret);", $content);

    $myfile = fopen("../config.inc.php", "w") or die("Unable to open file!");
    $txt = "$content";
    fwrite($myfile, $txt);
    fclose($myfile);
}

在以下字符串上:

<?php
# Bitte bearbeiten Sie diese Datei nicht. #

$mysql = array(  'host'=>'localhost',
                        'database'=>'schnnet',
                        'password'=>'root',
                        'user'=>'root');
$licence = array('key'=>'jZf5hhRd5vqmwTkMB9eq');
$rey_connect = array('active'=>true,'client_id'=>'123','client_secret'=>'123456');
?>

所以正则表达式可以完美运行 on phpliveregex,但在我的脚本中却不行。它不会以某种方式影响配置文件的内容。

您的代码运行良好:http://ideone.com/Gev03z

(尽管您不需要在替换字符串前加上 '\'。)

问题是您没有将 $content 写回文件。

更改 $content 只会更改文件中内容的本地副本。

编辑:

这显然不是正则表达式问题,而是文件权限问题。

当您调用 fwrite 时,您不会检查 return 是否为 false。在这种情况下,我希望它是,这意味着你不能写入文件。

现在除非我猜错了,否则是因为文件已经打开,因为 $fl。尝试在 $myfile.

之前添加 close($fl);
  1. 您是否将更改放回配置?
// this is really BAD approach
$content = file_get_contents("config");
$content = preg_replace(...);
file_put_contents("config", $content);
// or eval($content);
  1. 如果您想使用稍微不同的参数启动重新连接到数据库,您只需将您的代码片段移动到单独的函数并使用不同的参数调用它,例如你有一个名为 utils.php
  2. 的脚本
function connect($host, $db, $pwd, $user, $key, $id, $secret)
{
    $mysql = array('host'=>$host,
                   'database'=>$db,
                   'password'=>$pwd,
                   'user'=>$user);
    $licence = array('key'=>$key);
    $rey_connect = array('active'=>true,'client_id'=>$id,'client_secret'=>$secret);
}

然后将 utils.php 包含到另一个脚本中并在那里调用您的函数。

include_once 'utils.php';

connect(
 'localhost', 
 'schnnet', 
 'root, 
 'root', 
 'jZf5hhRd5vqmwTkMB9eq', 
 '123', 
 '123456');

更新:

我能够重现您描述的问题,但我的本地服务器上只有您的代码的 运行 简化版本,它现在似乎按预期工作。试试吧。

<?php
    function change()
    {
        $id = 'someId';
        $key = 'someKey';
        $secret = 'someSecret';
        $content = file_get_contents("config.php");

        $content = preg_replace("/(licence[^>]+)([^)]+)(.+)/si", ">'" . $key . "'", $content);
        $content = preg_replace("/(client_id[^>]+)([^,]+)(.+)/si", ">'" . $id . "'", $content);
        $content = preg_replace("/(client_secret[^>]+)([^)]+)(.+)/si", ">'" . $secret . "'", $content);

        file_put_contents("config.php", $content);
    }

    change();
?>