简体   繁体   中英

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. 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...

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:

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.

$ , [ and ] are special characters that's why you should escape them. \\s+ means whitespace characters 1 or more times.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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