in reply to Re: Twig Mixed Content Child Text Replace Issues
in thread Twig Mixed Content Child Text Replace Issues
Input: <paragraph> Some <bold>text</bold> here which may be any <bold>length< +/bold> and <bold>contain</bold> a number of child tags.</paragraph> Expected output: <paragraph> Some <bold>text</bold> here which may be any <bold>length< +/bold> and <bold>contain</bold> a quantity of child tags.</paragraph> Code: use XML::Twig; my $file = '<paragraph> Some <bold>text</bold> here which may be any < +bold>length</bold> and <bold>contain</bold> a number of child tags.</ +paragraph>'; my $twig = new XML::Twig(TwigHandlers => {'paragraph' => \¶graph} +,TwigRoots => {paragraph => 1}); $twig->parse($file); $twig->print; sub paragraph { my ($twig, $para,) = @_; my $para_text = $para->text; &choiceReplace($para,$para_text); } sub choiceReplace { my ($para,$para_text) = @_; my $search = "number"; #setting search and replace for example my $replace = "quantity"; #locate each occurrence of search term and prompt user to replace foreach ($para_text =~ /$search/) { my $new_version = $para_text; my $offset = 0; my $new_offset = 0; my $result = index($para_text, $search); my $new_result = index($new_version, $search); $offset = $result; $new_offset = $new_result; my $l = length ($search); #loop through string search results while found while (($result != -1) && ($new_result != -1)) { #create visuals for user to accept/deny match print "\n\nCurrent Version:\n $para_text"; my $replace_match = "**[[$replace]]**"; substr($new_version,$new_offset,$l) = $replace_match; print "\n\nMatched Version:\n $new_version"; print "\nWould you like to make this change (y or n)? "; chomp($change=<STDIN>); if ($change eq "n"){ my $nm_result = rindex($new_version, $replace_match); my $nm_l = length ($replace_match); my $no_match = "[DENIED]"; substr($new_version,$nm_result,$nm_l) = $no_match; } elsif ($change eq "y") { my $nm_result = rindex($new_version, $replace_match); my $nm_l = length ($replace_match); my $no_match = "[CHANGED]"; substr($new_version,$nm_result,$nm_l) = $no_match; substr($para_text,$offset,$l) = $replace; } #update search starting point $result = index($para_text, $search, $offset + 1); $offset = $result; $new_result = index($new_version, $search, $new_offset); $new_offset = $new_result; } #set text for <paragraph> @_[0]->set_text($para_text); } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Twig Mixed Content Child Text Replace Issues
by mirod (Canon) on Feb 08, 2011 at 16:18 UTC | |
by unknown_varmit (Initiate) on Feb 08, 2011 at 22:18 UTC |