[英]PHP regex adding items to array which that is into php file
in one of my php
file content have this below codes:在我的
php
文件内容之一中具有以下代码:
<?php
return [
// ...
'providers' => [
Illuminate\Auth\AuthServiceProvider::class,
// ...
],
'aliases' => [
// ...
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
],
];
here i want to know how can i add some item to providers
array and save it the same path with file name?在这里我想知道如何将一些项目添加到
providers
数组并将其保存在与文件名相同的路径中?
for exapmle i want to add Hekmatinasser\Verta\VertaServiceProvider::class
into array and array should be:例如,我想将
Hekmatinasser\Verta\VertaServiceProvider::class
到数组中,数组应该是:
<?php
return [
// ...
'providers' => [
Illuminate\Auth\AuthServiceProvider::class,
Hekmatinasser\Verta\VertaServiceProvider::class
// ...
],
//...
];
can we add and save it into file?我们可以添加并保存到文件中吗?
This is usually bad, and changing a config file like this, is not something i would do.这通常很糟糕,并且像这样更改配置文件不是我会做的事情。 There must be a better solution if you told us why you want to change the file.
如果您告诉我们您为什么要更改文件,那么一定有更好的解决方案。 But, a quick hack would look something like this.
但是,快速破解看起来像这样。
Instead of regex, i used a different approach, we can import the config array into a variable, loop over every item, and print it with the specific syntax, and some basic formatting.我使用了一种不同的方法,而不是正则表达式,我们可以将配置数组导入一个变量,遍历每个项目,并使用特定的语法和一些基本格式打印它。
$filename = "config.php";
$config = include $filename;
// Change array here, like this
$config['providers'][] = 'Hekmatinasser\Verta\VertaServiceProvider';
$string = "<?php\n\nreturn [\n";
foreach ($config as $key => $value) {
$string .= "\n\t'$key' => [\n";
if (isset($value[0])) {
// Numeric array
foreach ($value as $numeric_value) {
$string .= "\t\t$numeric_value::class,\n";
}
} else {
// Associative array
foreach ($value as $assoc_key => $assoc_value) {
$string .= "\t\t'$assoc_key' => $assoc_value::class,\n";
}
}
$string .= "\t\t\n],";
}
$string .= "\n\n];";
$file = fopen($filename, "w") or die("Unable to open file!");
fwrite($file, $string);
fclose($file);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.