Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm not sure I understand the nesting in your example, as the example doesn't demonstrate a purpose behind nesting. Your example input could very easily be</p> <pre><code>'This is my test {@a} {@b} string.' </code></pre> <p>And using arrays in str_replace would handle this very simply and quickly.</p> <pre><code>$aVars = array('{@a}' =&gt; 'hello', '{@b}' =&gt; 'world'); $sString = 'This is my test {@a} {@b} string.'; echo str_replace(array_keys($aVars), array_values($aVars), $sString); </code></pre> <p>Which gives us</p> <blockquote> <p>This is my test hello world string.</p> </blockquote> <p>Now, a recursive function for this isn't too difficult, though I'm not sure I understand how useful it would be. Here's a working example:</p> <pre><code>function template($sText, $aVars) { if (preg_match_all('/({@([^{}]+)})/', $sText, $aMatches, PREG_SET_ORDER)) { foreach($aMatches as $aMatch) { echo '&lt;pre&gt;' . print_r($aMatches, 1) . '&lt;/pre&gt;'; if (array_key_exists($aMatch[2], $aVars)) { // replace the guy inside $sText = str_replace($aMatch[1], $aVars[$aMatch[2]], $sText); // now run through the text again since we have new variables $sText = template($sText, $aVars); } } } return $sText; } </code></pre> <p>That print_r will show you what the matches look like so you can follow the function through its paces. Now lets try it out...</p> <pre><code>$aVars = array('a' =&gt; 'hello', 'b' =&gt; 'world'); $sStringOne = 'This is my test {@a} {@b} string.'; $sStringTwo = 'This is my test {@a{@b}} string.'; echo template($sStringOne, $aVars) . '&lt;br /&gt;'; </code></pre> <p>First Result:</p> <blockquote> <p>This is my test hello world string.</p> </blockquote> <p>Now lets try String Two</p> <pre><code>echo template($sStringTwo, $aVars) . '&lt;br /&gt;'; </code></pre> <p>Second Result:</p> <blockquote> <p>This is my test {@aworld} string.</p> </blockquote> <p>That may very well be what you're looking for. Obviously you would need an <code>aworld</code> variable for this to work recursively...</p> <pre><code>$aVars = array('a' =&gt; '', 'b' =&gt; '2', 'a2' =&gt; 'hello world'); echo template($sStringTwo, $aVars) . '&lt;br /&gt;'; </code></pre> <p>And our result.</p> <blockquote> <p>This is my test hello world string.</p> </blockquote> <p>And just for some fun with the recursion...</p> <pre><code>$aVars = array('a3' =&gt; 'hello world', 'b2' =&gt; '3', 'c1' =&gt; '2', 'd' =&gt; '1'); $sStringTre = 'This is my test {@a{@b{@c{@d}}}} string.'; echo template($sStringTre, $aVars) . '&lt;br /&gt;'; </code></pre> <blockquote> <p>This is my test hello world string.</p> </blockquote> <p>Not sure if this is what you're asking for...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload