How to insert content between 2nd and 3rd paragraphs in HTML using Perl?

I am trying to align a point between the 2nd and 3rd paragraphs to insert some content. The paragraphs are divided either into <p>or into two new lines, mixed. Here is an example:

text text text

text text text

<p>
text text text

text text text

</p>
<--------------------------- want to insert text here
<p>
text text text

text text text text

</p>

+3
source share
3 answers

Assuming there are no nested paragraphs ...

my $to_insert = get_thing_to_insert();
$text =~ s/((?:<p>.*?</p>|\n\n){2})/$1$to_insert/s;

should just do it.

With advanced formatting:

$text =~ s{
    (             # a group
        (?:       # containing ...
            <p>   # the start of a paragraph
            .*?   # to...
            </p>  # its closing tag
        |         # OR...
           \n\n   # two newlines alone. 
        ){2}      # twice
    )             # and take all of that...
}
{$1$to_insert}xms # and append $val to it

. \n\n ; Windows, \r\n\r\n, , , \r?\n\r?\n, \r .

, "\n\n" |, <p> - <p> - </p> . , <p> , .

+3

HTML-, , . HTML Perl InformIT.

- HTML:: TreeBuilder , HTML, . , . , , , .

HTML:: TreeBuilder :

#!perl
use strict;
use warnings;

use HTML::TreeBuilder;
use HTML::Element;

my $html  = HTML::TreeBuilder->new;
my $root  = $html->parse_file( *DATA );

my $second = ( $root->find_by_tag_name('p') )[1];

my $new_para = HTML::Element->new( 'p' );
$new_para->push_content( 'Add this line' );

$second->postinsert( $new_para );

print $root->as_HTML( undef, "\t", {} );

__END__
<p>
This is the first paragraph
</p>

<p>
This is the second paragraph
</p>

<p>
This is the last paragraph
</p>

, , HTML:: Tidy enclose_text .

0

my $text = '
text text text text
text text text text

<p>
text text text text
text text text text
</p>
<p>
text text text text
text text text text
</p>
';

:

our $cnt = 0;
our $where = 2;

my $new_stuff='<- want to insert text here';
$text =~ s/
           (
            (?:\n|<\/p>)\n
           )
           (?{ ++$cnt })
           (??{ $cnt==$where?'':'!$' })
          /$1$new_stuff\n/xs;

:

text text text text
text text text text

<p>
text text text text
text text text text
</p>
<- want to insert text here
<p>
text text text text
text text text text
</p>

-1

Source: https://habr.com/ru/post/1743219/


All Articles