title: Replacing spaces using regex in PHP
body: <p>I'm pretty new to regular expressions. I have a requirement to replace spaces in a piece of multi-line text. The replacement rules are these:</p>
  
  <ul>
  <li>Replace all spaces at start-of-line with a non-breaking space (<code>&amp;nbsp;</code>).</li>
  <li>Replace any instance of repeated spaces (more than one space together) with the same number of non-breaking-spaces.</li>
  <li>Single spaces which are not at start-of-line remain untouched.</li>
  </ul>
  
  <p>I used the <a href="http://www.weitz.de/regex-coach/" rel="nofollow noreferrer">Regex Coach</a> to build the matching pattern:</p>
  
  <pre><code>/( ){2,}|^( )/
  </code></pre>
  
  <p>Let's assume I have this input text:</p>
  
  <pre><code>asdasd asdasd  asdas1
   asda234 4545    54
    34545 345  34534
  34 345
  </code></pre>
  
  <p>Using a PHP regular expression replace function (like <a href="http://ch.php.net/manual/en/function.preg-replace.php" rel="nofollow noreferrer"><code>preg_replace()</code></a>), I want to get this output:</p>
  
  <pre><code>asdasd asdasd&amp;amp;nbsp;&amp;amp;nbsp;asdas1
  &amp;amp;nbsp;asda234 4545&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;54
  &amp;amp;nbsp;&amp;amp;nbsp;34545 345&amp;amp;nbsp;&amp;amp;nbsp;34534
  34 345
  </code></pre>
  
  <p>I'm happy doing simple text substitutions using regular expressions, but I'm having trouble working out how to replace multiple-times inside the match in order to get the output I desire.</p>