There are lots of questions and answers around the subject of valid php syntax from var outputs, what I am looking for is a quick and clean way of getting the output of var_export
to use valid php5.4 array syntax.
Given
$arr = [
'key' => 'value',
'mushroom' => [
'badger' => 1
]
];
var_export($arr);
outputs
array (
'key' => 'value',
'mushroom' =>
array (
'badger' => 1,
),
)
Is there any quick and easy way to have it output the array as defined, using square bracket syntax?
[
'key' => 'value',
'mushroom' => [
'badger' => 1
]
]
Is the general consensus to use regex parsing? If so, has anyone come across a decent regular expression? The value level contents of the arrays I will use will all be scalar
and array
, no objects or classes.
I realize this question is ancient; but search leads me here. I didn't care for full iterations or using
json_decode
, so here's apreg_replace
-basedvar_export
twister that gets the job done.I've tested it on several arrays and objects. Not exhaustively by any measure, but it seems to be working fine. I've made the output "tight" by also compacting extra line-breaks and empty arrays. If you run into any inadvertent data corruption using this, please let me know. I haven't benchmarked this against the above solutions yet, but I suspect it'll be a good deal faster. Enjoy reading your arrays!
As the comments have pointed out, this is just an additional syntax. To get the
var_export
back to the bracket stylestr_replace
works well if there are no)
in the key or value. It is still simple though using JSON as an intermediate:I used the HTML entities for
(
and)
. You can use the escape sequence or whatever.With https://github.com/zendframework/zend-code :
For anyone looking for a more modern-day solution, use the Symfony var-exporter, also available as a standalone library on composer, but included in Symfony default.
I had something similar laying around.
It's not overly pretty, but maybe sufficient for your case.
Any but the specified types are handled by the regular
var_export
. Thus for single-quoted strings, just comment out thestring
case.