in reply to Supplying the RHS to a regex as a variable
Which simply finds the first occurence of $start, then finds the next occurence after that of $end, and replaces that sub string with a new sub string. It's not quite as nice looking, but it doesn't break with random chars in between the start and end nodes. As it is now, it only replaces the first occurence of the start/end tags, but if you wanted to do it generally, you would just need to keep track of where ever the last $start or $end tag (your preference) was found and use that as the starting point for the next index.use strict; my $s = '<p>something something</p> <h2>blah </a> blah blah </h2> <p>something something</p>'; my $start = '<h2>'; my $end = '</h2>'; my $first = index($s,$start); my $last = index($s,$end,$first); substr($s, $first, $last-$first+length $end) = '<h1>'.substr($s,$first ++length $start,$last-$first-length $start).'</h1>'; print $s;
For the nested loops, assuming the existience of certain vars to simply things. This isn't tested at all however, and should be treated mostly as pseduo code.while(1) { if( index( substr( $s, $start_pos, $end_pos-$start_pos ), $start_t +ag ) != -1 ) { $end_pos = index( $s, $end_tag, ++$end_pos ); } else { last; # $end_pos is good } }
|
|---|