gpt4 book ai didi

php - 递归函数

转载 作者:行者123 更新时间:2023-12-04 05:50:17 24 4
gpt4 key购买 nike

我完全不知道,所以如果有人能指出我正确的方向,我将不胜感激。

我想要一个类似的东西

<?php
function square($num) {
// something
}

name('{3}'); // have this return 9
name('{6}'); // have this return 36
name('{{{2}}}'); // have this return 256
name('{9}{12}'); // have this return 81144
name('{{5}}'); // have this return 125
name('adscdc{4}{{3}}'); // have this return adscdc1681
?>

有人知道如何做到这一点吗?提前致谢 :)到目前为止,我有:

<?php
function square($text) {
$parts = explode('{', $text);
foreach($parts as $part) {
$piece = explode('}', $part);
$text = str_replace('{' . $piece[0] . '}', pow($piece[0], 2), $text);
}
return $text;
}
echo square('aasd{3}');
?>

最佳答案

我认为 {{5}} 应该是 625,对吧?

无论如何,尝试这样的事情:

<?php

function name ($str) {
while (1) {
preg_match('/{(\d+)}/', $str, $matches);
if (count($matches)<2) return $str;
$str=str_replace($matches[0], $matches[1]*$matches[1], $str);
}
}

echo "\n<pre>\n".
name('{3}'). // have this return 9
"\n".
name('{6}'). // have this return 36
"\n".
name('{{{2}}}'). // have this return 256
"\n".
name('{9}{12}'). // have this return 81144
"\n".
name('{{5}}'). // have this return 625
"\n".
name('adscdc{4}{{3}}'). // have this return adscdc1681
"\n</pre>\n";

?>

...运行得到了这些结果:

93625681144625adscdc1681

关于php - 递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3747633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com