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; }


In reply to Re: Regex to encode entities in XML by Anonymous Monk
in thread Regex to encode entities in XML by epoptai

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.