title: Is there an efficient way to run a sub-regex replace statement in a larger regex replace in php
body: <p>I am converting a handlebars template to be reusable within the compiled page.</p>
  
  <p>Sample code:</p>
  
  <pre><code>{{title}} 
  &lt;div id="desktop"&gt;
      {{#each menu}}
          &lt;a href="{{link}}"&gt;{{name}}&lt;/a&gt;
      {{/each}}
  &lt;/div&gt;
  </code></pre>
  
  <p>On the compiled page, I am wanting</p>
  
  <pre><code>Search Engines
  &lt;div id="desktop"&gt;
      &lt;a href="https://google.com"&gt;Google&lt;/a&gt;
      &lt;a href="https://yahoo.com"&gt;Yahoo&lt;/a&gt;
      &lt;script type="text/template" id="repeatable-menu"&gt;&lt;!--
          &lt;a href="{{link}}"&gt;{{name}}&lt;/a&gt;
      --&gt;&lt;/script&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>I am able to get halfway there by doing a regex replace on the template before it is compiled by handlebars and get the output</p>
  
  <pre><code>Search Engines
  &lt;div id="desktop"&gt;
      &lt;a href="https://google.com"&gt;Google&lt;/a&gt;
      &lt;a href="https://yahoo.com"&gt;Yahoo&lt;/a&gt;
      &lt;script type="text/template" id="repeatable-menu"&gt;&lt;!--
          &lt;a href=""&gt;&lt;/a&gt;
      --&gt;&lt;/script&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>by using the regex statement:</p>
  
  <pre><code>$templateHTML = preg_replace('/({{#each (.*?)}}(.*?){{\\/each}})/s', '$1&lt;script type="text/template" id="repeatable-$2"&gt;&lt;!--$3--&gt;&lt;/script&gt;', $templateHTML, -1);
  </code></pre>
  
  <p>Another alternative I have come up with is to break up the handlebars statements with something like this <code>&lt;a href="{|{link}|}"&gt;{|{name}|}&lt;/a&gt;</code> but I am unsure how to do that and preserve the {{title}} variable.</p>
  
  <p>would it be the wisest to run this code in a while loop until no replacements are made?</p>
  
  <pre><code>$templateHTML = preg_replace('/(&lt;script type="text\\/template" .*?\\&gt;&lt;!--.*?){{(.*?--\\&gt;\\&lt;\\/script\\&gt;)/s', '$1{|{$2', $templateHTML, -1, $count);
  </code></pre>