http://www.perlmonks.org?node_id=11105599


in reply to Match text from txt to html

Here is something to get you started. Using Mojo::DOM, parse the HTML, match a single sentence then alter the DOM to do what you want:

#!/usr/bin/perl use strict; use warnings; use Mojo::DOM; # slurp in from file, or get using Mojo::UserAgent... my $html = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional// +EN"> <html> <body> <p>This is sentence 1</p> <p>This is <font color="#000000"><font face="Century Gothic, serif">se +ntence 2</font></font></p> <p>This is sentence 1. This is sentence <span style="font-weight: norm +al">3</span> </p> </body> </html>'; # new Mojo::DOM my $dom = Mojo::DOM->new( $html ); # for each p tag found for my $e ( $dom->find('p')->each ){ # use the all_text method to get all of the visible text, including +from # descending tags. In this short example to get you started match a +specific # string. if ( $e->all_text eq 'This is sentence 2' ){ # once we have a match, wrap the node around this: $e->wrap_content('<sentence id="2"></sentence>'); } } # print to screen, do whatever you want with the results. print $dom->content;

Produces:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <body> <p>This is sentence 1</p> <p><sentence id="2">This is <font color="#000000"><font face="Century +Gothic, serif">sentence 2</font></font></sentence></p> <p>This is sentence 1. This is sentence <span style="font-weight: norm +al">3</span> </p> </body> </html>

Now all you have to do is make this generic, but that's fairly trivial, and I'll leave that as an exercise for you.

See also Re: Batch remove URLs or Super Search for more examples.

Update: I assume the ordering of the second p/sentence tag here was a mistake, closing the p tag before the sentene:

<p><sentence id=1>This is sentence 1></sentence></p> <p><sentence id=2>This is <font color="#000000"><font face="Century +Gothic, serif">sentence 2</font></font></p></sentence> <p><sentence id=3>This is sentence 1. </sentence><sentence id=4>Th +is is sentence <span style="font-weight: normal">3</span></sentence>< +/p>