Escaping XML to be used with SOAP
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);