htmlyoutubeperlvideo-embedding

Removing any videos from a HTML fragment


I have a (possibly not conforming to any standards) HTML fragment with embedded video. The problem is to remove the subfragment(s) with the video.

It is expected that the video follows this format:

<div data-oembed-url="https://www.youtube.com/watch?v=XXX&amp;feature=youtu.be"><iframe allowfullscreen="allowfullscreen" frameborder="0" height="270" src="https://www.youtube.com/embed/XXX?feature=oembed" tabindex="-1" width=" 480"></iframe></div>

I am entirely unsure whether all data follows this scheme.

I think any div or p containing only the video should be removed, too.

Please help to write Perl code to remove video. Which Perl module do you recommend to use for parsing?


Solution

  • sub RemoveVideo {
      my ($str) = @_;
    
      my $attrRe = qr/\s*(?<name>\b\S+\b)\s*=\s*(?<value>"[^"]*"|'[^']*'|[^"'<>\s]+)\s*/;
      my $iframeRe = qr{<iframe\b($attrRe)*>\s*</iframe\s*>|<iframe\b($attrRe)*\s*/>}i;
      my $divRe = qr{<div\b($attrRe)*>\s*$iframeRe\s*</div\s*>\s*}i;
      my $pRe = qr{<p\b($attrRe)*>\s*$iframeRe\s*</p\s*>\s*}i;
      $str =~ s/$divRe//gms;
      $str =~ s/$pRe//gms;
      $str =~ s/$iframeRe//gms; # "голый" iframe (не внутри дива)
    
      return $str;
    }
    my $Test = <<EOF;
    XXX
    <IFRAME allowfullscreen="allowfullscreen" frameborder="0" height="270" src="https://www.youtube.com/embed/XXX?feature=oembed" tabindex="-1" width=" 480"></iframe>
    <div data-oembed-url="https://www.youtube.com/watch?v=XXX&amp;feature=youtu.be"><iframe allowfullscreen="allowfullscreen" frameborder="0" height="270" src="https://www.youtube.com/embed/XXX?feature=oembed" tabindex="-1" width=" 480"></iframe></div>
    <p data-oembed-url="https://www.youtube.com/watch?v=XXX&amp;feature=youtu.be"><iframe allowfullscreen="allowfullscreen" frameborder="0" height="270" src="https://www.youtube.com/embed/XXX?feature=oembed" tabindex="-1" width=" 480"></iframe></p>
    YYY
    EOF
    
    print RemoveVideo($Test);