in reply to Regex to encode entities in XML

Hi there. I was looking for a solution to a similar problem earlier today - complicated by the fact that a string might already have entities in it, but might not. (XML files passed in by external content suppliers - ugh!)

I eventually built a solution around regexes, that I thought I'd share in case any body else finds it useful.

It should be easy to customise by altering just the first two lines - the first is the text to get replaced, the second the text to replace it with.

#NOTE: the first entry here is an extended regex that says, match an & + that is NOT followed by between 2 and 4 word characters and a semico +lon. #This should prevent it from double-encoding entites that already exis +t and hence corrupting the XML. my @entities_bare=qw/&(?!\w{2,4};) " ' < >/; my @entities_encoded=qw/&amp; &quot; &apos; &lt; &gt;/; sub encode_entities { my $string=shift; #print "trace: in encode_entities\n"; for(my $n=0;$n<scalar @entities_bare;++$n){ #print "encode_entities: searching for ".$entities_bare[$n]." +to replace with ".$entities_encoded[$n]."...\n"; if(not $string=~s/$entities_bare[$n]/$entities_encoded[$n]/g){ #print "encode_entities: WARNING: found no entites for ".$ +entities_bare[$n].".\n"; } } return $string; }