This is an unorthodox question, but there's a straightforward enough answer here that does not require a regex, so I will present this instead.
Assume that your config file is called config.php
and contains the code snippet that you provided in your example:
<?php
return [
'var1' => 'test1',
'var2' => 'test2',
'var3' => 'test3',
];
You can actually assign the return value of include
or require
to a variable. For example, in another script (assuming you are in the same directory) you can do this:
<?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);
This yields:
original config:
Array
(
[var1] => test1
[var2] => test2
[var3] => test3
)
updated config:
Array
(
[var1] => UPDATED!
[var2] => test2
[var3] => test3
)
I was originally a little surprised that you could use return
outside of the context of a function/method, but it's perfectly valid. You learn something new every day... This use case is actually documented under the documentation for include
- refer to Example #5 include and the return statement for more details.
Please note, that if you are using include
or require
to pull in untrusted or external scripts, the usual security considerations apply. This is discussed in the documentation linked above.
Also, if your included file contains a syntax error, then you will probably get a parse error
or similar, but I guess that's an obvious point!
Edit
Finally, I should point out that your question does not ask how to save the updated configuration back into the file, but you did leave a comment underneath that suggests that you want to do this also.
However, if you want to update and persist a configuration on file, I would definitely using a more malleable method to write/read this data to/from disk - perhaps json_encode()
and json_decode
, serialize()
and unserialize()
.
Nevertheless, here's a naive solution in which you can write your updated config:
// ...
// 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)));
Further reading:
Hope this helps :)