[英]How to strip comments from Php/Html source? (with sed/awk/grep etc..)
I would like to remove comments from the source code of PHP files using Shell Script or AppleScript. 我想使用Shell Script或AppleScript从PHP文件的源代码中删除注释。 (I'm using Codekit OS X App hooks)
(我正在使用Codekit OS X App挂钩)
I tried to do it with sed or grep commands, but the modern regex codes I'm used to with PHP / javascript don't work. 我试图用sed或grep命令来做到这一点,但是我习惯于PHP / javascript的现代正则表达式代码不起作用。
https://regex101.com/r/awpFe0/1/ https://regex101.com/r/awpFe0/1/
Demo it will be enough to tell me what I want to do. 演示足以告诉我我想做什么。
I need a working version on the command line. 我需要在命令行上使用工作版本。
I found this, but I can't get exactly the result I want: https://stackoverflow.com/a/13062682/6320082 我找到了这个,但是我无法得到我想要的结果: https : //stackoverflow.com/a/13062682/6320082
I've been working it for two days. 我已经工作了两天。 Please help me.
请帮我。
Example contents: 示例内容:
Test string // test comment
Test string// test comment
echo 1;//test comment
http://domain.ltd // test comment
$wrong_slashes = "http://domain.ltd/asd//asd//asd";
function test() { // test comment
Test string /* test comment // test comment */
Test string //test /* test */
Test string /* test comment /* */ */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
/**
multi-line comments
*/
<script src="//cdn.com/site.js">
$pattern = "([//])";
$pattern = '([//])';
<!-- html comments -->
<div>test</div> <!-- html comments -->
<!-- html comments --> <div>test</div>
If Perl is your option, try something like: 如果您选择Perl,请尝试以下操作:
perl -e '
while (<>) {
$str .= $_; # slurps all lines into a string for multi-line matching
}
1 while $str =~ s#/\*(?!.*/\*).*?\*/##sg;
# removes C-style /* comments */ recursively
$str =~ s#(?<!:)//[^\x27"]*?$##mg;
# removes // comments not preceded by ":" and not within quotes
$str =~ s#<!--.*?-->##sg;
# removes <!-- html comments -->
print $str;
' example.txt
which outputs: 输出:
Test string
Test string
echo 1;
http://domain.ltd
$wrong_slashes = "http://domain.ltd/asd//asd//asd";
function test() {
Test string
Test string
Test string
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<script src="//cdn.com/site.js">
$pattern = "([//])";
$pattern = '([//])';
<div>test</div>
<div>test</div>
Let me excuse that the script above might be optimized to the given sample and it will be easy to find bizarre codes with which my answer doesn't work. 让我原谅,上面的脚本可能已针对给定的示例进行了优化,并且很容易找到我的答案不起作用的奇怪代码。 It may be close to impossible to write a flawless regex to match
comments
without the designated parser of the language. 没有语言的指定解析器,编写完美的正则表达式以匹配
comments
可能几乎是不可能的。
I've solved it by running PHP CLI with shell script. 我已经通过使用Shell脚本运行PHP CLI解决了该问题。 I did what I wanted using the example in the url with PHP.
我使用了PHP网址中的示例,做了我想做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.