-
-
Save mcaskill/65fb0621ce413fd8f66e70062000d3c0 to your computer and use it in GitHub Desktop.
PHP var_export() with short array syntax (square brackets) indented 2 spaces.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* PHP var_export() with short array syntax (square brackets) indented 2 spaces. | |
* | |
* @todo Fix edge case where if a string value has `=>\n[` it will get converted to `=> [`. | |
* | |
* @link https://www.php.net/manual/en/function.var-export.php | |
* | |
* @param mixed $expression | |
* @param bool $return | |
* @return string|void | |
*/ | |
function varexport($expression, bool $return = false) { | |
$export = var_export($expression, true); | |
$patterns = [ | |
'/array \(/' => '[', | |
'/^([ ]*)\)(,?)$/m' => '$1]$2', | |
'/=>[ ]?\n[ ]+\[/' => '=> [', | |
'/([ ]*)(\'[^\']+\') => ([\[\'])/' => '$1$2 => $3', | |
'/[0-9]+ => /' => '', | |
]; | |
$export = preg_replace(array_keys($patterns), array_values($patterns), $export); | |
if ($return) { | |
return $export; | |
} | |
echo $export; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$array = [ | |
'str' => 'Test | |
spaces', | |
0 => 33, | |
1 => TRUE, | |
[3,4,'d',[]], | |
'arr' => [ | |
'text with spaces' => '[Tes\'t"s": | |
=> [ | |
=> | |
[ | |
{ | |
spaces', | |
], | |
"str2" => "Test's' | |
} spaces", | |
'arr2' => [ | |
'text with spaces' => [ | |
'arr3' => [ | |
'text with spaces' => 'Te": "st \' => [ | |
spaces', | |
], | |
], | |
], | |
]; | |
varexport($array); | |
// Result: | |
``` | |
[ | |
'str' => 'Test | |
spaces', | |
0 => 33, | |
1 => true, | |
2 => [ | |
0 => 3, | |
1 => 4, | |
2 => 'd', | |
3 => [ | |
], | |
], | |
'arr' => [ | |
'text with spaces' => '[Tes\'t"s": | |
=> [ | |
=> [ | |
{ | |
spaces', | |
], | |
'str2' => 'Test\'s\' | |
} spaces', | |
'arr2' => [ | |
'text with spaces' => [ | |
'arr3' => [ | |
'text with spaces' => 'Te": "st \' => [ | |
spaces', | |
], | |
], | |
], | |
] | |
``` | |
NOTE: The only issue is when a string value has `=>\n[`, it will get converted to `=> [`. See lines 11-12 vs line 47. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment