从PHP文件中删除注释的最佳方法是什么?我想做一些与strip-whitespace()类似的事情-但它也不应该删除换行符。例如:我要这个:<?PHP// somethingif ($whatsit) { do_something(); # we do something here echo '<html>Some embedded HTML</html>';}/* another long comment*/some_more_code();?>成为:<?PHPif ($whatsit) { do_something(); echo '<html>Some embedded HTML</html>';}some_more_code();?>(尽管如果在删除注释的地方仍然留有空行,那是不可能的)。由于可能需要保留嵌入式html,因此这可能是不可能的-那是什么导致了google上出现的问题。
3 回答
不负相思意
TA贡献1777条经验 获得超10个赞
我会使用tokenizer。这是我的解决方案。它应该同时在PHP 4和5上运行:
$fileStr = file_get_contents('path/to/file');
$newStr = '';
$commentTokens = array(T_COMMENT);
if (defined('T_DOC_COMMENT'))
$commentTokens[] = T_DOC_COMMENT; // PHP 5
if (defined('T_ML_COMMENT'))
$commentTokens[] = T_ML_COMMENT; // PHP 4
$tokens = token_get_all($fileStr);
foreach ($tokens as $token) {
if (is_array($token)) {
if (in_array($token[0], $commentTokens))
continue;
$token = $token[1];
}
$newStr .= $token;
}
echo $newStr;
- 3 回答
- 0 关注
- 950 浏览
添加回答
举报
0/150
提交
取消