Home >Backend Development >PHP Tutorial >请问一个字符串截取的有关问题

请问一个字符串截取的有关问题

WBOY
WBOYOriginal
2016-06-13 10:21:12850browse

请教一个字符串截取的问题
哪个高手有空帮我看一个函数,弄半天了不行

PHP code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?phpfunction 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;?>


按单词从前面截取字符串,控制在30个字符以内的长度,调试半天,不知道函数内部哪里不对,返回值为空,奇怪了,请高手帮我看看,多谢了,在线等着。

------解决方案--------------------
PHP code
$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>
PHP code
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>
PHP code
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>
PHP code
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>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn