我需要一个正则表达式在数组中搜索,然后返回该键的值。
例如:我想得到var1
密钥的值。
我的配置
<?php
return [
'var1' => 'test1',
'var2' => 'test2',
'var3' => 'test3'
];
?>
则应返回test1
这是一个非正统的问题,但这里有一个足够简单的答案,不需要正则表达式,所以我将介绍这个问题。
假设您的配置文件名为config.php
,并且包含您在示例中提供的代码片段:
<?php
return [
'var1' => 'test1',
'var2' => 'test2',
'var3' => 'test3',
];
实际上,您可以将include
或require
的返回值分配给一个变量。例如,在另一个脚本中(假设您在同一目录中),您可以执行以下操作:
<?php
// your config file...
$file = __DIR__ . '/config.php';
// ensure the file exists and is readable
if (!is_file($file) || !is_readable($file)) {
throw new RuntimeException(
sprintf('File %s does not exist or is not readable!', $file)
);
}
// include file and assign to variable `$config`
// which now contains the returned array
$config = include $file;
echo 'original config:' . PHP_EOL;
print_r($config);
// update config key `var1`
$config['var1'] = 'UPDATED!';
echo 'updated config:' . PHP_EOL;
print_r($config);
这产生:
original config:
Array
(
[var1] => test1
[var2] => test2
[var3] => test3
)
updated config:
Array
(
[var1] => UPDATED!
[var2] => test2
[var3] => test3
)
我最初有点惊讶,你可以在函数/方法的上下文之外使用return
,但它是完全有效的。你每天都在学习新东西。。。这个用例实际上记录在include
的文档中——有关更多详细信息,请参阅示例#5include和return语句。
请注意,如果使用include
或require
引入不受信任的或外部脚本,则通常需要考虑安全性。以上链接的文档对此进行了讨论。
此外,如果包含的文件包含语法错误,那么您可能会得到parse error
或类似的文件,但我想这是显而易见的!
编辑
最后,我应该指出,您的问题并没有询问如何将更新后的配置保存回文件中,但您确实在下面留下了一条评论,表明您也希望这样做。
然而,如果您想在文件上更新和持久化配置,我肯定会使用一种更具延展性的方法将这些数据写入磁盘/从磁盘读取这些数据——可能是json_encode()
和json_decode
,serialize()
和unserialize()
。
尽管如此,这里有一个简单的解决方案,您可以在其中编写更新的配置:
// ...
// file has to be writeable!
if (!is_writeable($file)) {
throw new RuntimeException(
sprintf('File %s is not writeable!', $file)
);
}
file_put_contents($file,
sprintf('<?php return %s;', var_export($config, true)));
进一步阅读:
is_file()
is_readable()
is_writeable()
file_put_contents()
var_export()
希望这有帮助:)