我正在学习php并希望尝试递归。我已经做了一个功能,它得到一个字,如果它的长度超过30个字符,它分成两半。而且我做了一个递归,所以如果其中的一半超过30个单词,它就会将其分开等等。递归无法按预期方式工作
function breakLongWords($val) {
$array = explode(" ", $val);
foreach ($array as $key => $word) {
if (strlen($word) > 30) {
for ($i = strlen($word) + 1; $i >= round(strlen($word)/2); $i--) {
$word[$i+1] = $word[$i];
if ($i == round(strlen($word)/2)) {
$word[$i] = " ";
}
}
breakLongWords($word);
$array[$key] = $word;
}
$result = implode(" ", $array);
}
var_dump($result);
}
$str = "SuperDuperExtraGiggaDoubleTrippleSpicyWithCheeseLongUnlimitedString123";
breakLongWords($str);
我使用var_dump函数在repl.it中测试它。不知怎的,最后的结果是一个分为两半而不是四个(70个字符)的词条。但是其中一个“var_dumps”输出正确的结果。
string(37) "SuperDuperExtraGigg aDoubleTrippleSpi"
string(35) "cyWithCheeseLongUn limitedString123"
string(73) "SuperDuperExtraGigg aDoubleTrippleSpi cyWithCheeseLongUn limitedString123"
string(71) "SuperDuperExtraGiggaDoubleTrippleSpi cyWithCheeseLongUnlimitedString123"
你能帮我解决这个问题吗?
https://repl.it/repls/SeveralBountifulCub
请大家在这个问题上的样子:https://stackoverflow.com/questions/2648968/什么是递归函数在PHP中 - 你的代码有几个错误。 – 1stthomas
你为什么使用爆炸? –
@KshitijKumar函数接收的字符串可以包含多个单词。所以我将字符串转换为单词数组并检查它们中的每一个。 –