Replace & with &

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
revof11
Forum Newbie
Posts: 16
Joined: Tue Jan 18, 2005 7:30 am
Location: Mountain Top, PA
Contact:

Replace & with &

Post 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;
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

use negative assertions
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

What if I use < do you want to convert that to &lt;?
User avatar
revof11
Forum Newbie
Posts: 16
Joined: Tue Jan 18, 2005 7:30 am
Location: Mountain Top, PA
Contact:

Post by revof11 »

Good question...
No..

Hmmmm.. that definitely complicates the issue....
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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
Post Reply