Skip to content

Instantly share code, notes, and snippets.

@michaeluno

michaeluno/example.php

Last active Jan 21, 2020
Embed
What would you like to do?
A custom function that beautifies PHP print_r() outputs.
<?php
class A {
public function test() {}
}
$_func = function( $f ) use ( $p ) {};
$_resource = fopen( __DIR__ . '_temp.txt', 'w' );
$_oA = new A;
$_sMultiLine =<<<HERE
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vivamus maximus, dui in facilisis porta, lacus erat molestie turpis, non aliquam leo ipsum sed eros.
Integer ultrices, diam ut gravida aliquam, ipsum tortor vestibulum magna, eu auctor purus nisl sit amet felis.
Morbi ex dui, laoreet vitae tellus ac, condimentum mollis lectus. Nullam luctus tortor ac magna pulvinar hendrerit.
Ut vestibulum, velit eu mollis viverra, neque diam rhoncus arcu, eget condimentum turpis sem vel mi.
Sed pretium magna at magna eleifend convallis.
Fusce mattis justo vel purus egestas, malesuada imperdiet tortor sollicitudin.
HERE;
$a = [
'first' => [
'second' => [
'third' => [
'fourth' => [
'string' => '4th depth string value',
'array' => [],
'integer' => 12345,
'decimal' => 0.987654,
'boolean' => true,
],
'multiline' => $_sMultiLine,
],
'empty_array' => [],
],
0 => 'zero key',
'' => 'empty key',
],
'object' => $_oA,
'function' => $_func,
'callable' => [ $_oA, 'test' ],
'file' => $_resource,
];
$sOutput = print_r( $a, true );
echo $sOutput;
$sOutput = getPrintR( $a );
echo $sOutput;
function getPrintR( $v ) {
$_sOutput = print_r( $v, true );
$_aNeedles = [
// Fix extra line breaks after `Array()`
10 => '/\)([\r\n]\n?)(?=([\r\n]\n?)\s*(\)|\[.*\] \=\> ))/',
// Fix empty array or object output
11 => '/(Array|[A-Za-z]+ Object)\K([\r\n]\n?)\s+\(([\r\n]\n?)\s+\)/',
// Fix redundant line breaks
12 => '/(Array|[A-Za-z]+ Object)\K(([\r\n]\n?)\s*\()/',
// Fix redundant indents
/// Make all indents 8 spaces to be consistent; add all lines to have 4 white spaces
20 => '/[\r\n]\n?\K(\s{4}.*)(?=\[.*\] \=\> )/',
/// Convert 8 space indents into 4 spaces
21 => '/'
. '(\G|[\r\n]\n?)\K' // previous match point | linebreak
. '[^\S\r\n]{8}' // the 8 white spaces to convert
. '(?=.*' // look-forward
. '(?<lf>' // named group `lf`
. '\[.*\] \=\> '
. '|' // or
. '(?<cp>' // named group `cp` closing parenthesis
. '\)[\r\n]\n?'
. '(?<cp2>'
. '\k<cp>'
. '|'
. '[^\S\r\n]+\[.*\] \=\> '
. '|'
. '([^\S\r\n]+|.*)\)[\r\n]\n?'
. ')'
. ')'
. ')'
. ')' // end look-forward
. '/',
];
$_aReplaces = [
10 => ')',
11 => '()',
12 => '(',
20 => '$1 ',
21 => ' ',
];
return preg_replace( $_aNeedles, $_aReplaces, $_sOutput );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment