日期:2014-05-17 浏览次数:20472 次
<?php function glstrlen($str) { $tmp_array = explode(",",$str); if(strlen($str)>30) { array_pop($tmp_array); $str = implode(",",$tmp_array); if(strlen($str)>30) { glstrlen($str); } else { return $str; } } else { return $str; } } $strs = "Woods,trees,grass ,grassland,Yellow, motorcycle,highway"; $a = glstrlen($strs); echo $a; ?>
$strs = "Woods,trees,grass ,grassland,Yellow, motorcycle,highway"; $array = explode(',' , $strs); print_r(array_pad($array,30,'.'));
------解决方案--------------------
array_pop:将数组最后一个单元弹出(出栈),返回的是弹出的单元,并不是弹出最后一个单元后的数组。
------解决方案--------------------
由于这是递归,所以你的return只是退出到上一层
function glstrlen($str) { $tmp_array = explode(",",$str); if(strlen($str)>30) { // var_dump($str); array_pop($tmp_array); $str = implode(",",$tmp_array); if(strlen($str)>30) { // 加了个判断,如果有返回值,那么就退出,这样层层退出,调用才算结束 if(!is_null($str = glstrlen($str)) ) { return $str; } } else { return $str; } } else { return $str; } }
------解决方案--------------------
function glstrlen($str) { $arr =explode(',', $str); while(strlen($str) > 30) { array_pop($arr); $str = join(',', $arr); } return $str; } echo glstrlen("Woods,trees,grass ,grassland,Yellow, motorcycle,highway");
------解决方案--------------------
function glstrlen($str) { if(strlen($str)>30) { $tmp_array = explode(",",$str); array_pop($tmp_array); $str = implode(",",$tmp_array); return glstrlen($str); } return $str; } $strs = "Woods,trees,grass ,grassland,Yellow, motorcycle,highway"; $a = glstrlen($strs); echo $a;