如何用另一个变量替换所有全局变量?

How to replace all global variables by another variable?

我正在尝试将示例中的所有全局变量替换为特定值 $var,如下例所示:

(example.php)

<?php 
// before
$firstname = $_GET['firstname'];
$lastname = $_POST['lastname'];
$age = $_REQUEST['age'];
?>

如上例所示,我想将 php 文件中的任何全局变量 $_POST, $_GET, $_REQUEST 自动更改为 php 文件中的特定值 $var

这是我获取每一行并检查代码行是否有 $_POST$_GET$_REQUEST 的方法,然后我尝试更改任何全局变量在文件中设置为特定值 $var

(test.php)

<?php
$file = file_get_contents("example.php");
$lines = explode("\n", $file);

$var = '$var';
foreach ($lines as $key => &$value) {

if(strpos($value, '$_GET') !== false){
     // Replace $_GET['firstname'] and put $var
}
elseif(strpos($value, '$_POST') !== false){
     // Replace $_POST['lastname'] and put $var
}
elseif(strpos($value, '$_REQUEST') !== false){
     // Replace $_REQUEST['age'] and put $var
}

}
?>

将任何全局变量替换为 $var 后的预期结果如下:

(example.php)

<?php

// The expected results to be after replace all global variables by $var
// This is how I expect the file to looks like after replace

$firstname = $var;
$lastname = $var;
$age = $var;

?>

如果有人能帮我找到合适的方法来用 $var 替换文件中存在的任何 $_GET, $_POST, $_REQUEST,我将不胜感激。

<?php
$firstname = $var;  // Just change text (remove $_GET['firstname', and put $var] in php file
$lastname = $var;  // Just change text (remove $_POST['lastname', and put $var] in php file
$age = $var;  // Just change text (remove $_REQUEST['age', and put $var] in php file
?>

解法:

下面的代码会将 $_REQUEST['thisvar'] 转换为 $thisvar,以及您设置的任何其他 $_GET/$_POST 变量。

如评论中所述,$_REQUEST 涵盖 $_GET$_POST

foreach($_REQUEST as $key => $value) $$key = $value;

如果我修改你的例子:

$file = file_get_contents("example.php");
$lines = explode("\n", $file);

foreach($lines as $key => $value) $$key = $value;

这是你想要的吗?

$file = file_get_contents("example.php");
$lines = explode("\n", $file);

$var = '$var';
foreach ($lines as $key => &$value) {

    if(strpos($value, '$_GET') !== false){
        $value = preg_replace('/$_GET\[.+?\]/', $var, $value);
    }
    elseif(strpos($value, '$_POST') !== false){
        $value = preg_replace('/$_POST\[.+?\]/', $var, $value);
    }
    elseif(strpos($value, '$_REQUEST') !== false){
        $value = preg_replace('/$_REQUEST\[.+?\]/', $var, $value);
    }
}

See Regex Demo

/$_(GET|POST|REQUEST)\[[^\]]*\]/' 将匹配,例如 $_GET[anything-other-than-a-right-bracket] 我们所要做的就是将其替换为 $var 并重写文件:

<?php
$file = file_get_contents("example.php");
$file = preg_replace('/$_(GET|POST|REQUEST)\[[^\]]*\]/', '$var', $file);
file_put_contents("example.php", $file);