簡體   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