繁体   English   中英

如何从PHP / HTML来源中删除评论? (使用sed / awk / grep等。)

[英]How to strip comments from Php/Html source? (with sed/awk/grep etc..)

我想使用Shell Script或AppleScript从PHP文件的源代码中删除注释。 (我正在使用Codekit OS X App挂钩)

我试图用sed或grep命令来做到这一点,但是我习惯于PHP / javascript的现代正则表达式代码不起作用。

https://regex101.com/r/awpFe0/1/

演示足以告诉我我想做什么。

我需要在命令行上使用工作版本。

我找到了这个,但是我无法得到我想要的结果: https : //stackoverflow.com/a/13062682/6320082

我已经工作了两天。 请帮我。

示例内容:

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>

如果您选择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

输出:

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>

让我原谅,上面的脚本可能已针对给定的示例进行了优化,并且很容易找到我的答案不起作用的奇怪代码。 没有语言的指定解析器,编写完美的正则表达式以匹配comments可能几乎是不可能的。

我已经通过使用Shell脚本运行PHP CLI解决了该问题。 我使用了PHP网址中的示例,做了我想做的事情。

示例功能

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM