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

revision f528b6f44d8f3950cdf9510a048976a26ede99c3

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