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

问题描述 投票:0回答:1

我正在尝试将示例中的所有全局变量替换为特定值$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;

?>

[如果有人可以帮助我找到一种用$_GET, $_POST, $_REQUEST替换文件中存在的$var的合适方法,我将不胜感激。

php regex replace str-replace regular-language
1个回答
0
投票

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

foreach($_REQUEST as $key => $value) $$key = $value;
© www.soinside.com 2019 - 2024. All rights reserved.