简体   繁体   English

从PHP源获取数组键和值

[英]Get array keys and values from PHP source

I'm writing a config editor. 我正在编写配置编辑器。 I'm reading in the file with fopen and fgets line by line. 我正在逐行读取带有fopen和fgets的文件。 I want to get the array keys and values from the string. 我想从字符串中获取数组键和值。 I'm not familiar with regex thats why i'm asking. 我不了解正则表达式,所以我要问。

Example config file: 配置文件示例:

$conf['something'] = 'value';
$conf['other_thing']['another_key'] = 3000;

I can't loop through the $conf array, as it is a SuperObject in the system, and holds many additional datas, even inited classes... 我无法遍历$ conf数组,因为它是系统中的SuperObject,并且包含许多其他数据,甚至是初始化的类...

I would do smth like this: 我会做这样的事情:

// get config file as a variable
require_once('config_file.php');

// get keys
$keys = array_keys($conf);

// get config file as a variable
$values = array_values($conf);

While not direct answer to your question but as you wrote "I'm writing a config editor." 虽然不是您问题的直接答案,但是当您写到“我正在编写配置编辑器”时。 then I assume you also write this config file down. 那么我假设您也将这个配置文件写下来。 So assuming your editor keeps config in $conf array while it works, I'd just dump it as JSON instead of your PHP code: 因此,假设您的编辑器在工作时将配置保存在$conf数组中,我将其转储为JSON而不是您的PHP代码:

file_put_contents('config.json', json_encode($conf));

and then read it back when needed 然后在需要时将其读回

$conf = json_decode( file_get_contents('config.json') );

\\$conf\\['(.*?)']\\s+=\\s+'(.*?)'; here is your pattern. 这是你的模式。 Key is in the group 1 and value is in the group 2. 键在组1中,值在组2中。

$ , [ and ] are special characters that's why you should escape them. $[]是特殊字符,这就是为什么您应该转义它们。 \\s+ means whitespace characters 1 or more times. \\s+表示空白字符1次或多次。

Here is your regex: 这是您的正则表达式:

\$conf(\[('.*')\])+\s?=\s?(.*);

The first matches are your keys, last one your value 第一个匹配项是您的键,最后一个匹配项是您的值

As this is php array you can directly loop through it, and get required key value pairs else you can you can use php's functions array_keys for fetching all keys from the $conf array and array_values for getting array values 由于这是php数组,因此您可以直接遍历它,并获取必需的键值对,否则您可以使用php的函数array_keys从$ conf数组中获取所有键,并使用array_values获取数组值

or else 要不然

if you want to create a config editor try using ini file php has a good support for creating and using config files see this function parse_ini_file this is a standard way for creating config file if you have too key value pairs 如果要创建配置编辑器,请尝试使用ini文件php对创建和使用配置文件有很好的支持,请参见此函数parse_ini_file,这是创建键值对的标准方法,如果键值对过多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM