【问题标题】:How to strip comments from Php/Html source? (with sed/awk/grep etc..)如何从 Php/Html 源中删除注释? (使用 sed/awk/grep 等)
【发布时间】:2019-04-23 11:57:42
【问题描述】:

我想使用 Shell Script 或 AppleScript 从 PHP 文件的源代码中删除 cmets。 (我正在使用 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>

【问题讨论】:

    标签: regex bash sed command-line grep


    【解决方案1】:

    如果 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>
    

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

    【讨论】:

      【解决方案2】:

      我已经通过运行带有 shell 脚本的 PHP CLI 解决了这个问题。我使用 PHP 的 url 中的示例做了我想做的事。

      example function

      【讨论】:

        猜你喜欢
        • 2023-03-18
        • 2014-10-27
        • 2015-10-19
        • 2014-11-16
        • 2012-08-02
        • 1970-01-01
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多