请教一个字符串截取的问题
哪个高手有空帮我看一个函数,弄半天了不行
<!--
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>
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号