如何在php中删除单行注释(例如“ //删除此注释”)? [英] How to remove single line comments in php (eg "// remove this comment")?
问题描述
我想使用正则表达式从代码中删除所有单行注释(例如 // comments
)。
I want to remove all single line comments (eg //comments
) from my code using regular expression.
现在我正在使用: preg_replace('/ \ / \ /(.*)/','',$ html);
但它也会删除像 http://example.com
之类的字符串。
By now I'm using: preg_replace('/\/\/(.*)/','',$html);
but it also removes strings like http://example.com
.
推荐答案
您不能可靠地做到这一点。不能保证文件中任何位置的 //
都表示在PHP上下文中有注释。例如,它很可能包含在字符串中。
You cannot do this reliably. There is no guarantee that //
at any position in a file indicates a comment in PHP context. It might very well be contained in a string for example.
只能通过一些让步来实现这一点。例如,如果在一行上捕获 //条评论
就足够了,那么这将是一个误报较少的选项:
It's only possible to approach this with a few concessions. For example if it is sufficient if it catches // comments
on a single line, then this would be an option with less false positives:
$source = preg_replace('#^\s*//.+$#m', "", $source);
真正的解决方案是利用语言解析器,但这显然太过分了。因此,请尝试添加一些启发式方法,以避免删除错误的地方。
The real solution would be utilize a language parser, but that's obviously overkill. So try with adding some heuristics to avoid removing wrong occourences.
这篇关于如何在php中删除单行注释(例如“ //删除此注释”)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!