php中递归调用的原理,PHP如何进行递归函数调用?

我不确定我是否理解您的示例中的嵌套,因为该示例没有演示嵌套背后的目的。您的示例输入很容易

'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。

不确定这是否是你想要的…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值