PHP var_export() with short array syntax (square brackets) indented 4 spaces

revision 296c0b5e231427e2baa118cb7d1eb1af0df45ac9

raw

varexport.php

1
2
3
4
5
6
7
8
9
10
11
12
<?php
function varexport($expression, $return=FALSE, $indent=4) {
    $object = json_decode(str_replace(['(', ')'], ['&#40', '&#41'], json_encode($expression)), TRUE);
    $export = str_replace(['array (', ')', '&#40', '&#41'], ['[', ']', '(', ')'], var_export($object, TRUE));
    $export = preg_replace("/ => \n[^\S\n]*\[/m", ' => [', $export);
    $export = preg_replace("/ => \[\n[^\S\n]*\]/m", ' => []', $export);
    $spaces = str_repeat(' ', $indent);
    $export = preg_replace("/([ ]{2})(?![^ ])/m", $spaces, $export);
    $export = preg_replace("/^([ ]{2})/m", $spaces, $export);
    if ((bool)$return) return $export; else echo $export;
}
 

History