简体   繁体   中英

Removing starting and ending tags from a string in Perl

I have a string like this :

<script>This String may contain other JS tags in between </script>

My requirement is to remove starting and ending Script tag from the string , If the string has some other tags in between , those should NOT be removed.

How can I do this in Perl ?

尝试以下perl一种衬垫:

perl -lpe "s/<\/?script>//g" inputfile

在perl中:

$string =~ s!<script[^>]*>|.*</\s*script>!!g;

You could try the below code to remove the opening and the closing script tags.

"<script>This String may contain other JS tags in between </script>".replace(/^<script>|<\/script>$/g, "");
'This String may contain other JS tags in between '

OR

"foo <script>This String may contain other JS tags in between </script> foo".replace(/^((?:(?!<script>).)*)<script>(.*?)<\/script>((?:(?!<script>).)*)$/g, "$1$2$3");
'foo This String may contain other JS tags in between  foo'

Through perl,

$ echo 'foo <script>This String may contain other JS tags in between </script> foo' | perl -pe 's/^((?:(?!<script>).)*)<script>(.*?)<\/script>((?:(?!<script>).)*)$/\1\2\3/g'
foo This String may contain other JS tags in between  foo

In perl you can do a test to check if it matches your tags, and then do substitution.

#!/usr/bin/perl

use warnings; 
use strict;

my $string = '<script>This String may contain other JS tags in between </script>';

if ( $string =~ /^(<script>).*(<\/script>)$/ ) {
$string =~ s/$1|$2//g;
}
print $string, "\n";

this will print:

This String may contain other JS tags in between

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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