Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am trying to use perl to format some html as follows: I want to enclose ever occurrence of $a with $a. However I only want to replace $a when it occurs outside of the html tags already present. In other words, do a s/$a/$a/g except when the $a is somewhere between a < and a >

Replies are listed 'Best First'.
Re: Replace characters not in html tags
by gjb (Vicar) on Oct 31, 2002 at 23:11 UTC

    You could use a HTML parser to find tags and text, and do a replacement on the text while writing out everything you find. This is the cleanest thing to do.

    Alternatively, use a two-level approach, first find tags, then replace the $a in the parts of the input that were skipped between matches on tags.

    Hope this helps, -gjb-

Re: Replace characters not in html tags
by dingus (Friar) on Nov 01, 2002 at 11:26 UTC
    To match $a only in data not enclosed in tags you need a regex of
    />[^<]*$a/s;
    to replace $a with $b only in data not enclosed in tags you need
    s/(>[^<]*)$a/$1$b/sg;