猿问

自动从PHP代码中删除注释的最佳方法

从PHP文件中删除注释的最佳方法是什么?


我想做一些与strip-whitespace()类似的事情-但它也不应该删除换行符。


例如:


我要这个:


<?PHP

// something

if ($whatsit) {

    do_something(); # we do something here

    echo '<html>Some embedded HTML</html>';

}

/* another long 

comment

*/

some_more_code();

?>

成为:


<?PHP

if ($whatsit) {

    do_something();

    echo '<html>Some embedded HTML</html>';

}

some_more_code();

?>

(尽管如果在删除注释的地方仍然留有空行,那是不可能的)。


由于可能需要保留嵌入式html,因此这可能是不可能的-那是什么导致了google上出现的问题。


鸿蒙传说
浏览 951回答 3
3回答

不负相思意

我会使用tokenizer。这是我的解决方案。它应该同时在PHP 4和5上运行:$fileStr = file_get_contents('path/to/file');$newStr&nbsp; = '';$commentTokens = array(T_COMMENT);if (defined('T_DOC_COMMENT'))&nbsp; &nbsp; $commentTokens[] = T_DOC_COMMENT; // PHP 5if (defined('T_ML_COMMENT'))&nbsp; &nbsp; $commentTokens[] = T_ML_COMMENT;&nbsp; // PHP 4$tokens = token_get_all($fileStr);foreach ($tokens as $token) {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (is_array($token)) {&nbsp; &nbsp; &nbsp; &nbsp; if (in_array($token[0], $commentTokens))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; $token = $token[1];&nbsp; &nbsp; }&nbsp; &nbsp; $newStr .= $token;}echo $newStr;

慕姐4208626

如何使用php -w生成一个去除注释和空格的文件,然后使用PHP_Beautifier之类的美化器重新设置格式以提高可读性?
随时随地看视频慕课网APP
我要回答