Regular Expression To Find Single Apersands In Text

22nd September 2008

Encoding special characters in a block of HTML or other code can be a pain because there might already be ampersands there that impart encoding. This might be an ampersand that has already been encoded with a &, or it might be an ampersand in the code as an if statement or similar.

Use the following regular expression to find any ampersand that hasn't already been encoded.

([^&])&(?!#?[a-zA-Z0-9]{2,6};|\$|&)

When using replace, you can turn any ampersand into & by using the following replace.

$1&

The only problem with this statement is when the code uses a & operator as part of a statement to do bitwise operations.

Add new comment

The content of this field is kept private and will not be shown publicly.