问题描述
我在 PHP 中编写了一个递归函数来裁剪文本.裁剪后的文本将...附加到末尾.未裁剪的文本将以其原始状态返回.
I have written a recursive function in PHP to crop text. The cropped text will have ... attached to the end. Non-cropped text will be returned in its original state.
如果文本适合最大宽度则有效.但是,如果它不适合给定的宽度,该函数将不会返回值,但应该返回值.似乎整个 return 语句都被忽略了.如果我用 echo 替换返回,它会显示正确的值.
It works if the text fits the max width. However, if it does not fit in the given width the function will not return a value but it should. It seems that the whole return statement is ignored. If I replace the return with echo, it shows the correct value.
预期结果:
-TEST ZIN
-TEST ZI
-测试 Z
-测试
-TES
-TE...(此处没有返回任何内容,因此永远不会显示)
The expected result:
-TEST ZIN
-TEST ZI
-TEST Z
-TEST
-TES
-TE... (nothing is returned here so this will never be shown)
function check_length($str, $max, $size = SIZE, $rec = false) {
echo "FUNCTION $str ";
list($left, , $right) = imageftbbox($size, 0, FONTURL, $str);
if($rec == false) {
if(($right - $left) > $max) {
echo 'if 1<br />';
check_length(substr($str, 0, -1), $max, $size, true);
} else {
echo 'else 1<br />';
return $str;
}
} else {
if(($right - $left) > ($max - 9)) {
echo 'if 2<br />';
check_length(substr($str, 0, -1), $max, $size, true);
} else {
echo 'else 2<br />';
return "$str...";
}
}
}
echo check_length('TEST ZIN', 30);
注意:函数中的echo用于调试.
NOTE: the echo's in the function are for debugging.
提前致谢.
推荐答案
您没有正确返回文本,例如
You're not returning the text properly e.g.
} else {
echo 'else 1<br />';
return $str; <---nothing in the 'parent' caller catches this, so it's lost
}
任何进行递归并需要返回值的地方,都必须捕获/返回递归调用本身:
Anywhere you do recursion and need to return a value, you must capture/return the recursive call itself:
return check_length(substr($str, 0, -1), $max, $size, true);
或
$newstr = check_length(...);
return $newstr;
这篇关于PHP递归函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!