PHP正则表达式将项添加到数组中,该数组位于PHP文件中



在我的一个php文件内容中有以下代码:

<?php
return [
// ...
'providers' => [
IlluminateAuthAuthServiceProvider::class,
// ...
],

'aliases' => [
// ...
'Form' => CollectiveHtmlFormFacade::class,
'Html' => CollectiveHtmlHtmlFacade::class,
],
];

在这里,我想知道如何向providers数组添加一些项,并将其保存在与文件名相同的路径中?

例如,我想将HekmatinasserVertaVertaServiceProvider::class添加到数组中,数组应该是:

<?php
return [
// ...
'providers' => [
IlluminateAuthAuthServiceProvider::class,
HekmatinasserVertaVertaServiceProvider::class
// ...
],

//...
];

我们可以添加并保存到文件中吗?

这通常很糟糕,我不愿意更改这样的配置文件。如果您告诉我们为什么要更改文件,一定有更好的解决方案。但是,快速破解会是这样的。

我使用了一种不同的方法,而不是regex,我们可以将配置数组导入一个变量,在每个项目上循环,并使用特定的语法和一些基本格式打印它。

$filename = "config.php";
$config = include $filename;

// Change array here, like this
$config['providers'][] = 'HekmatinasserVertaVertaServiceProvider';

$string = "<?phpnnreturn [n";
foreach ($config as $key => $value) {
$string .= "nt'$key' => [n";
if (isset($value[0])) {
// Numeric array
foreach ($value as $numeric_value) {
$string .= "tt$numeric_value::class,n";
}
} else {
// Associative array
foreach ($value as $assoc_key => $assoc_value) {
$string .= "tt'$assoc_key' => $assoc_value::class,n";
}
}
$string .= "ttn],";
}
$string .= "nn];";

$file = fopen($filename, "w") or die("Unable to open file!");
fwrite($file, $string);
fclose($file);