TobyInkster.co.uk
17/07/2007: Pretty Printing for PHP
Here’s a PHP function for reformatting the whitespace in PHP code:
<?php
define('SC_STANDARD_BRACES', 0);
define('SC_IMPROVED_BRACES', 1);
define('SC_WEIRDASS_BRACES', 2);
function sc_pp ($sourcecode, $outmode=SC_STANDARD_BRACES)
{
$sourcecode = "<?php\n{$sourcecode}\n?>\n";
$indentlevel = 0;
$output = '';
foreach(token_get_all($sourcecode) as $token)
{
if (is_array($token))
list($tokentype, $spelling) = $token;
else
list($tokentype, $spelling) = array(NULL, $token);
if ($tokentype==T_WHITESPACE && preg_match('/\s$/', $output))
continue;
elseif ($tokentype==T_WHITESPACE)
$spelling = ' ';
if ($spelling=='{')
{
$indentlevel++;
if ($outmode==SC_IMPROVED_BRACES)
$output .= "\n$indent";
elseif ($outmode==SC_WEIRDASS_BRACES)
$output .= "\n$indent\t";
}
elseif ($spelling=='}')
{
$indentlevel--;
$output = preg_replace('/\t$/i', '', $output);
if ($outmode==SC_WEIRDASS_BRACES)
$output .= "\t";
}
$indent = str_repeat("\t", $indentlevel);
$output .= $spelling;
if ($spelling==';'||$spelling=='{'||$spelling=='}')
$output .= "\n$indent";
}
return $output;
}
$sc = 'echo "1";if (FALSE){echo 2;
echo 2; echo 2; if( TRUE ){echo 3;}}echo 4;';
print sc_pp($sc, 1);
?>
Comments
Comment 001
I tried running it on itself and got an error off line 51.
13:02:37 [brussel@/ioBin]> ./pp.php pp.php
./pp.php: line 51: syntax error near unexpected token `{echo’
./pp.php: line 51: `$sc = ‘echo “1”;if (FALSE){echo 2;’
13:02:42 [brussel@/ioBin]>
Date: Saturday, 11th August 2007, 9:02pm (BST)
Comment 002
I put the above code in a file called pp.php and ran it against itself. I’m probably calling it all wrong but since I didn’t see any details about running it I assumed it would be the obvious…
Anyways it blows up on line 51. I figured you probably want comments.
13:02:37 [brussel@/ioBin]> ./pp.php pp.php
./pp.php: line 51: syntax error near unexpected token `{echo’
./pp.php: line 51: `$sc = ‘echo “1”;if (FALSE){echo 2;’
13:02:42 [brussel@/ioBin]>
Date: Saturday, 11th August 2007, 9:12pm (BST)
Comment 003
13:02:37 [brussel@/ioBin]> ./pp.php pp.php
./pp.php: line 51: syntax error near unexpected token `{echo’
./pp.php: line 51: `$sc = ‘echo “1”;if (FALSE){echo 2;’
13:02:42 [brussel@/ioBin]>
Date: Saturday, 11th August 2007, 9:13pm (BST)
Comment 004
your comment form does not work!
Date: Saturday, 11th August 2007, 9:14pm (BST)
Comments are moderated and may take one or two days to show up on the site. You can bypass comment moderation by signing up as a registered user.