Escaping XML to be used with SOAP I'm attempting to escape ampersands from a string before passing to PHP's SimpleXMLElement-&gt;addChild() for use with some SOAP webservices, but I don't want to double escape them. I'm getting these strings from a variety of sources so I can't count on them not being escaped already.  &amp;amp;amp; or &amp;amp; should be untouched but &amp; or &amp;blah blah blah should not.

&lt;?php $s = preg_replace('/&amp;([^; ]*)( |$)/','&amp;amp;$1$2',$s)
Your code is hard to read, and a few test cases would be nice to know what this should handle. For example, do you want to allow multiple lines? Do you want to replace things that are not "amp", like &amp;gt;? Are you sure this will correctly sanitize your inputs?

It seems to me that you only want to replace &amp; (ampersand + space) by &amp;amp;. 

This version works:


for any kind of whitespace 
across multiple lines:




$s = preg_replace('/&amp;(\s)/m', '/&amp;amp;$1/', $s);