@@ -14,11 +14,12 @@ my $parent = $text->parentNode; my $preceding = $parent->insertBefore('XML::LibXML::Text'->new($before), $text); - $parent->insertAfter('XML::LibXML::Text'->new($after), $text); + my $following + = $parent->insertAfter('XML::LibXML::Text'->new($after), $text); my $tag = 'XML::LibXML::Element'->new($tag_name); $parent->replaceChild($tag, $text); $tag->{query} = $query; - return $preceding + return $preceding, $following } my $xml = "The quick brown fox"; @@ -50,12 +51,14 @@ my $subtext_length = sum(map length, @texts[ $from .. $to ]); my $last_pos = length($texts[$to]) - ($subtext_length - $found - length $query); - my $preceding = insert_tag($texts[$to], $last_pos, 'end', $query); + my @new_texts = insert_tag($texts[$to], $last_pos, 'end', $query); + + splice @texts, $to, 1, @new_texts; + + my $start_text = $from == $to ? $new_texts[0] : $texts[$from]; - my $start_text = $from == $to ? $preceding : $texts[$from]; insert_tag($start_text, $found, 'start', $query); - @texts = $dom->findnodes('//text()'); $from += $from == $to ? 1 : 2; last OUTER if $from > @texts;