regex (in PHP) to match & that aren't HTML entities

Here's the goal: to replace all standalone ampersands with & but NOT replace those that are already part of an HTML entity such as  .

I think I need a regular expression for PHP (preferably for preg_ functions) that will match only standalone ampersands. I just don't know how to do that with preg_replace.

Answers


You could always run html_entity_decode before you run htmlentities? Works unless you only want to do ampersands (and even then you can play with the charset parameters).

Much easier and faster than a regex.


PHP's htmlentities() has double_encode argument for this.

If you want to do things like that in regular expressions, then negative assertions come useful:

preg_replace('/&(?![a-z#]+;)/i','&',$txt);

Need Your Help

Is Apple's iPhone magnetometer calibration working properly?

ios iphone calibration magnetometer

I'm currently developing an iPhone App (on iPhone 5, iOS 7, Xcode 5) which requires a very accurate determination of the current attitude. The "attitude" of CMDeviceMotion does not fulfil these

Can I convert to Swift in Titanium?

node.js swift titanium titanium-studio

I'm building an app in Titanium in node.js. For my targets I have Android and iOS but I want my iOS target to output native iOS in Swift and not in objective-c.