Page 1 of 1

Replace & with &

Posted: Sun Oct 08, 2006 9:51 am
by revof11
I would like to run a replace on any instances of & in a string with &
I have the base condition working (just replacing &) but cannot get the "not" condition.

Here's a "formal" description of the regex requirement:

Code: Select all

Replace all instances of & with & where & is not already followed by amp;

Posted: Sun Oct 08, 2006 11:51 am
by Weirdan
use negative assertions

Posted: Mon Oct 09, 2006 6:50 pm
by Ollie Saunders
What if I use < do you want to convert that to &lt;?

Posted: Mon Oct 09, 2006 8:32 pm
by revof11
Good question...
No..

Hmmmm.. that definitely complicates the issue....

Posted: Mon Oct 09, 2006 8:50 pm
by Ollie Saunders
use negative assertions
negative lookahead

Code: Select all

function htmlAmp($str)
{
    return preg_replace('/&(?![a-z]+;)/i', '&', $str);
}
assert(htmlAmp('&') == '&');
assert(htmlAmp('<') == '<');
assert(htmlAmp('Bangers&Mash') == 'Bangers&Mash');
// no output == works