Maison >développement back-end >tutoriel php > 请问一个字符串截取的有关问题
请教一个字符串截取的问题
哪个高手有空帮我看一个函数,弄半天了不行
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> <?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,'.')); <br><font color="#e78608">------解决方案--------------------</font><br>array_pop:将数组最后一个单元弹出(出栈),返回的是弹出的单元,并不是弹出最后一个单元后的数组。 <br><font color="#e78608">------解决方案--------------------</font><br>由于这是递归,所以你的return只是退出到上一层<br>
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; } } <br><font color="#e78608">------解决方案--------------------</font><br>
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"); <br><font color="#e78608">------解决方案--------------------</font><br>
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; <div class="clear"> </div>