Um die Kommentare aus einer PHP-Datei zu entfernen werden die beiden PHP-Konstanten T_COMMENT und T_DOC_COMMENT verwendet die Funktion token_get_all() um den Dateiinhalt aufzusplitten.
Dann wird verglichen ob der Inhalt ein Kommentar ist.
<?php /*********************************************************************** * Php-Script umd Kommentare, Leezeichen und Leerzeilen zu entfernen * Stand 17.11.2020 * Version 1.3 ***********************************************************************/ define('NL', "\n"); define('TB', "\t"); define('WS', ' '); /*********************************************************************** *** Functions *** ***********************************************************************/ function removePhpComments($str){ $commentTokens = [ \T_COMMENT, \T_DOC_COMMENT, ]; $str = str_replace("\r", '', $str); $tokens = token_get_all($str); $s = ''; foreach ($tokens as $token) { if (is_array($token)) { if (in_array($token[0], $commentTokens)) { if (substr($token[1], -1) == NL) $s .= NL; # keep \n from comment with \n at end of comment string continue; } $token = $token[1]; } $s .= $token; } return $s; } function removeEmptyLines($str, $max = false) { # delete whitespace at end of line do { $str = str_replace(WS . NL, NL, $str); } while (strpos($str, WS . NL) > 0); # delete tab at end of line do { $str = str_replace(TB . NL, NL, $str); } while (strpos($str, TB . NL) > 0); if ($max === true) { $find = NL . NL; $replace = NL; } else { $find = NL . NL . NL; $replace = NL . NL; } do { $str = str_replace($find, $replace, $str); } while (strpos($str, $find) > 0); return $str; } # Should be run at last function removeSpaces ($str) { # delete double spaces do { $str = str_replace(WS . WS, WS, $str); } while (strpos($str, WS . WS) > 0); # deletespaces at start of line do { $str = str_replace(NL . WS, NL, $str); } while (strpos($str, NL . WS) > 0);
# delete tab at start of line do { $str = str_replace(NL . TB, NL, $str); } while (strpos($str, NL . TB) > 0); return $str; } function cleanfile($file) { if (substr($file, -4) == '.php') { $str = file_get_contents($file); $str = removePhpComments($str); $str = removeEmptyLines($str); #$str = removeSpaces($str); if ($GLOBALS['keep_org'] === true) { $file = str_replace('.php', '.comment_free.php', $file); } file_put_contents($file, $str); } } /*********************************************************************** *** Einstellungen *** ***********************************************************************/ # File or Folder to cleanup $file_folder_org = 'org.php'; # keep original file (stongly recommended set to true) $keep_org = true; /*********************************************************************** *** Programm *** ***********************************************************************/ if (file_exists($file_folder_org)) { if (is_dir($file_folder_org)) { $files = scandir($file_folder_org); foreach ($files as $key => $value) { cleanfile($value); } } else { cleanfile($file_folder_org); } } ?>