我不确定我是否理解您的示例中的嵌套,因为该示例没有演示嵌套背后的目的。您的示例输入很容易
'This is my test {@a} {@b} string.'
在str_replace中使用数组可以非常简单和快速地处理这个问题。
$aVars = array('{@a}' => 'hello', '{@b}' => 'world');
$sString = 'This is my test {@a} {@b} string.';
echo str_replace(array_keys($aVars), array_values($aVars), $sString);
给我们
这是我的测试hello world string。
现在,这个递归函数并不太难,尽管我不确定它有多有用。下面是一个工作示例:
function template($sText, $aVars) {
if (preg_match_all('/({@([^{}]+)})/',
$sText, $aMatches, PREG_SET_ORDER)) {
foreach($aMatches as $aMatch) {
echo '
' . print_r($aMatches, 1) . '';
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;
}
该打印将向您显示匹配项的外观,这样您就可以通过其步调跟踪函数。现在让我们试试看……
$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) . '
';
第一个结果:
这是我的测试hello world string。
现在让我们试试第二串
echo template($sStringTwo, $aVars) . '
';
第二个结果:
这是我的测试@aworld字符串。
这很可能是你想要的。显然你需要一个
aworld
变量用于递归工作…
$aVars = array('a' => '', 'b' => '2', 'a2' => 'hello world');
echo template($sStringTwo, $aVars) . '
';
以及我们的结果。
这是我的测试hello world string。
为了让递归更有趣…
$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) . '
';
这是我的测试hello world string。
不确定这是否是你想要的…