Regular Expression to Encode Ampersands

This handy regex will encode ampersands ( & ) without double-encoding other html entities:


// replace just '&' that are NOT html special chars
$str = preg_replace( "/&(?!([a-zA-Z] |#[0-9] |#x[0-9a-fA-F] );)/", '&', $str );

IE: it will not turn   into   or ' into '

Top