php截取字符串函数(不打断单词)的方法
程序员文章站
2024-02-20 17:09:46
...
在项目中,遇到一个需求,如我要截取一串字符串,而又不想截取半截的单词,看了下php手册的这个mb_strimwidth() 函数,据说是不会打断单词的,可是测试没有成功,于是乎自己写个先,虽然有些小问题,但是勉强能用了,有时间再封装的好点. 该函数的实现原理是利用wordwrap()打断单词,然后用mb_strlen()计算单词的长度,截取到需要被截取的长度即可. 如下测试:
//原字符串
$str = ‘readonly this boolean attribute indicates that the user cannot modify the value of the control. Unlike the disabled attribute, the readonly attribute does not prevent the user from clicking or selecting in the control. long ge blog\’s The value of a read-only control is still submitted with the form.’;
echo wordcut($str,100);
//结果:
readonly this boolean attribute indicates that the user cannot modify value of control. Unlike disabled attribute, …
/**
* 该函数截取英文字符串,不会打断英文单词,就是说不会把一个单词截取一半
* note: 不适用于中文,当然改改也可以
* note: 目前该函数有点小bug,$cutlength 不是指长度,而是计算所有单词的长度到了这个数时停止,其实也就是空格的长度被忽略了
*/
function wordcut($string, $cutlength = 250, $replace = ‘…’){
//长度不足直接返回
if(mb_strlen($string) return $string;
}else{
//计算当前单词总长度
$totalLength = 0;
$datas = $newwords = array();
//打乱文本
$wrap = wordwrap($string,1,"\t");
//组成数组
$wraps = explode("\t",$wrap);
foreach ($wraps as $tmp){
//计算每个单词的长度
$datas[$tmp] = mb_strlen($tmp);
}
foreach ($datas as $word => $length){
//保存单词的总长度
$totalLength += $length;
//如果小于截取的长度则保存
if($totalLength array_push($newwords,$word);
}else{
break;
}
}
//生成新字符串
$str = trim(implode(” “,$newwords));
return empty($str) ? $str : $str.’ ‘.$replace;
}
}
//原字符串
$str = ‘readonly this boolean attribute indicates that the user cannot modify the value of the control. Unlike the disabled attribute, the readonly attribute does not prevent the user from clicking or selecting in the control. long ge blog\’s The value of a read-only control is still submitted with the form.’;
echo wordcut($str,100);
//结果:
readonly this boolean attribute indicates that the user cannot modify value of control. Unlike disabled attribute, …
/**
* 该函数截取英文字符串,不会打断英文单词,就是说不会把一个单词截取一半
* note: 不适用于中文,当然改改也可以
* note: 目前该函数有点小bug,$cutlength 不是指长度,而是计算所有单词的长度到了这个数时停止,其实也就是空格的长度被忽略了
*/
function wordcut($string, $cutlength = 250, $replace = ‘…’){
//长度不足直接返回
if(mb_strlen($string) return $string;
}else{
//计算当前单词总长度
$totalLength = 0;
$datas = $newwords = array();
//打乱文本
$wrap = wordwrap($string,1,"\t");
//组成数组
$wraps = explode("\t",$wrap);
foreach ($wraps as $tmp){
//计算每个单词的长度
$datas[$tmp] = mb_strlen($tmp);
}
foreach ($datas as $word => $length){
//保存单词的总长度
$totalLength += $length;
//如果小于截取的长度则保存
if($totalLength array_push($newwords,$word);
}else{
break;
}
}
//生成新字符串
$str = trim(implode(” “,$newwords));
return empty($str) ? $str : $str.’ ‘.$replace;
}
}
本文来源:http://www.52blogger.com/archives/819
下一篇: 正确理解PHP开发MVC模型
推荐阅读
-
php截取字符串函数(不打断单词)的方法
-
php使用number_format函数截取小数的方法分析
-
php对包含html标签的字符串进行截取的函数分享
-
php字符串截取函数的方法(支持中文截取 )
-
php返回字符串中所有单词的方法
-
PHP使用strstr()函数获取指定字符串后所有字符的方法,strstr字符串_PHP教程
-
PHP使用json_encode函数时不转义中文的解决方法,
-
真正根据utf8编码的规律来进行截取字符串的函数(utf8版sub_str )_php技巧
-
fgetcsv函数不能读取csv文件中文字符串的解决方法_PHP教程
-
可以保证单词完整性的PHP英文字符串截取代码分享_php实例