如何使用 preg_replace 删除以 // 开头的注释行,而不是像 http:// 这样的 url
我需要从我的代码中删除注释行。
preg_replace('!//(.*)!', '', $test);
效果很好。但它也删除了网站网址并留下了像http这样的网址:
所以为了避免这种情况,我把同样的内容放在 preg_replace('![^:]//(.*)!', '', $test); 中。
工作正常。但问题是,如果我的代码具有如下所示的行,
$code = 'something';// comment here
它将用分号替换注释行。那是在替换我上面的代码之后,
$code = 'something'
所以它会生成错误。
我只需要删除单行注释,网址应该保持不变。
请帮忙。提前致谢
I need to remove the comment lines from my code.
preg_replace('!//(.*)!', '', $test);
It works fine. But it removes the website url also and left the url like http:
So to avoid this I put the same like preg_replace('![^:]//(.*)!', '', $test);
It's work fine. But the problem is if my code has the line like below
$code = 'something';// comment here
It will replace the comment line with the semicolon. that is after replace my above code would be
$code = 'something'
So it generates error.
I just need to delete the single line comments and the url should remain same.
Please help. Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试一下
,还可以阅读有关 PCRE 断言的更多信息 http://cz.php.net /manual/en/regexp.reference.assertions.php
try this
also read more about PCRE assertions http://cz.php.net/manual/en/regexp.reference.assertions.php
如果您想解析 PHP 文件并操作它包含的 PHP 代码,最好的解决方案(即使有点困难)是使用 Tokenizer :它的存在是为了允许操作 PHP 代码。
Working with regular expressions for such a thing is a bad idea...
例如,您想到了
http://
;但是包含//
的字符串又如何呢?比如这个:
If you want to parse a PHP file, and manipulate the PHP code it contains, the best solution (even if a bit difficult) is to use the Tokenizer : it exists to allow manipulation of PHP code.
Working with regular expressions for such a thing is a bad idea...
For instance, you thought about
http://
; but what about strings that contain//
?Like this one, for example :
这很快就会变得复杂。
//
在字符串中还有更多用途。如果您正在解析 PHP 代码,我强烈建议您查看 PHP tokenizer< /a>.它是专门为解析 PHP 代码而设计的。问题:您为什么要首先尝试删除评论?
编辑:我现在看到您正在尝试解析 JavaScript,而不是 PHP。那么,为什么不使用 javascript 压缩器呢?它将删除注释、空格并执行更多操作以使您的文件尽可能小。
This can get complicated fast. There are more uses for
//
in strings. If you are parsing PHP code, I highly suggest you take a look at the PHP tokenizer. It's specifically designed to parse PHP code.Question: Why are you trying to strip comments in the first place?
Edit: I see now you are trying to parse JavaScript, not PHP. So, why not use a javascript minifier instead? It will strip comments, whitespace and do a lot more to make your file as small as possible.