You are here: Re: php code formating « PHP Programming Language « IT news, forums, messages
Re: php code formating

Posted by Toby A Inkster on 05/29/07 20:52

Jon Slaughter wrote:

> that is, I want to take a string of php code and add white space and line
> feeds to make it readable.... my simple method of adding newlines after ;'s
> and {'s don't work well cause some strings contain substrings with code in
> it that should not be parsed.

You could try something like:

<?php

$sourcecode = 'echo "1";if(FALSE){echo 2;echo 2; echo 2; if(TRUE){echo 3;}}echo 4;';
$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 ($spelling=='{')
{
$indentlevel++;
}
elseif ($spelling=='}')
{
$indentlevel--;
$output = preg_replace('/\t$/i', '', $output);
}

$indent = str_repeat("\t", $indentlevel);
$output .= $spelling;
if ($spelling==';'||$spelling=='{'||$spelling=='}')
$output .= "\n$indent";
}

print $output;

?>


--
Toby A Inkster BSc (Hons) ARCS
[Geek of HTML/SQL/Perl/PHP/Python/Apache/Linux]
[OS: Linux 2.6.12-12mdksmp, up 95 days, 3:39.]

Non-Intuitive Surnames
http://tobyinkster.co.uk/blog/2007/05/25/non-intuitive-surnames/

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация