How can I strip HTML in a string using Perl?

后端 未结 3 1801
青春惊慌失措
青春惊慌失措 2021-02-04 12:59

Is there anyway easier than this to strip HTML from a string using Perl?

$Error_Msg =~ s|||ig;
$Error_Msg =~ s|||ig;
$Error_Msg =~ s|

        
3条回答
  •  没有蜡笔的小新
    2021-02-04 13:06

    From perlfaq9: How do I remove HTML from a string?


    The most correct way (albeit not the fastest) is to use HTML::Parser from CPAN. Another mostly correct way is to use HTML::FormatText which not only removes HTML but also attempts to do a little simple formatting of the resulting plain text.

    Many folks attempt a simple-minded regular expression approach, like s/<.*?>//g, but that fails in many cases because the tags may continue over line breaks, they may contain quoted angle-brackets, or HTML comment may be present. Plus, folks forget to convert entities--like < for example.

    Here's one "simple-minded" approach, that works for most files:

    #!/usr/bin/perl -p0777
    s/<(?:[^>'"]*|(['"]).*?\1)*>//gs
    

    If you want a more complete solution, see the 3-stage striphtml program in http://www.cpan.org/authors/id/T/TO/TOMC/scripts/striphtml.gz .

    Here are some tricky cases that you should think about when picking a solution:

    A > B
    
    A > B
    
    
    
    
    
    <# Just data #>
    
    >>>>>>>>>>> ]]>
    

    If HTML comments include other tags, those solutions would also break on text like this:

    
    

提交回复
热议问题