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
'This is my test {@a} {@b} string.'
And using arrays in str_replace would handle this very simply and quickly.
$aVars = array('{@a}' => 'hello', '{@b}' => 'world');
$sString = 'This is my test {@a} {@b} string.';
echo str_replace(array_keys($aVars), array_values($aVars), $sString);
Which gives us
This is my test hello world string.
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:
function template($sText, $aVars) {
if (preg_match_all('/({@([^{}]+)})/',
$sText, $aMatches, PREG_SET_ORDER)) {
foreach($aMatches as $aMatch) {
echo '<pre>' . print_r($aMatches, 1) . '</pre>';
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;
}
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...
$aVars = array('a' => 'hello', 'b' => 'world');
$sStringOne = 'This is my test {@a} {@b} string.';
$sStringTwo = 'This is my test {@a{@b}} string.';
echo template($sStringOne, $aVars) . '<br />';
First Result:
This is my test hello world string.
Now lets try String Two
echo template($sStringTwo, $aVars) . '<br />';
Second Result:
This is my test {@aworld} string.
That may very well be what you're looking for. Obviously you would need an aworld
variable for this to work recursively...
$aVars = array('a' => '', 'b' => '2', 'a2' => 'hello world');
echo template($sStringTwo, $aVars) . '<br />';
And our result.
This is my test hello world string.
And just for some fun with the recursion...
$aVars = array('a3' => 'hello world', 'b2' => '3', 'c1' => '2', 'd' => '1');
$sStringTre = 'This is my test {@a{@b{@c{@d}}}} string.';
echo template($sStringTre, $aVars) . '<br />';
This is my test hello world string.
Not sure if this is what you're asking for...