a script to auto tab a php file
Some of my files are tabbed badly or not at all so thought it would be good to find a way to auto tab them. I wrote a script to do it. It does the following:
1) Opens all the files one by one in a directory that are .php
2) Remvoes all whitespace and then adds appropriate amount of tabs based on { and }
3) It does not add tabs to lines with //// or #### in (i did not want my longer comments tabbed but did my // comments that go at the end of the line.
BUGS:
1) If you have { or } in use on a line (for example in a regex) this won't work. It needs to be modified to check only the first letter and last letter of a line really.
2) A way to remove if ($action == "do") { echo "do"; } and convert it to multiple lines would be good.
3) Convert if ($action == "do") echo "do";
would also be useful but harder i guess.
4) It only does one directory, going recurisvly through all directories would be really good.
p.s. the formatting of this script is wrong because it suffers from bug 1 and gets updated while running.
BACKUP YOUR FILES BEFORE RUNNING!
PHP Code:
$dir = opendir(".");
while ($file = readdir($dir)) {
if (strstr($file, ".php")) {
$fcontents = file($file);
while (list ($line_num, $line) = each ($fcontents)) {
if (strstr($line, "}")) {
$tab--;
}
if (!((strstr($line, "\\\\")) OR (strstr($line, "####")))) {
$new_file .= growstring("\t", $tab);
}
$new_file .= trim($line) . "\r\n";
if (strstr($line, "{")) {
$tab++;
}
}
$file2 = fopen($file, "w");
fputs($file2, $new_file);
unset($new_file);
unset($tab);
}
}
function growstring($string, $number) {
for ($idx = 0; $idx < $number; ++$idx) {
$newstring .= $string;
}
return $newstring;
}