php截取字符串函数分享
作者:hebedich 时间:2023-11-14 10:53:21
经常看到有新手问PHP有没有类似asp的left函数或right函数,实现截取某字符串左边或右边开始N个字符的函数。答案当然是有的。PHP中的substr函数就可以做的到,只不过PHP把二个函数合二为一了,这里再给大家分享一个更加优秀的截取字符串的函数。
/**
* 方法库-截取字符串-【该函数作者未知】
* @param string $string 字符串
* @param int $length 字符长度
* @param string $dot 截取后是否添加...
* @param string $charset编码
* @return string
*/
public function cutstr($string, $length, $dot = ' ...', $charset = 'utf-8') {
if (strlen($string) <= $length) {
return $string;
}
$string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string);
$strcut = '';
if (strtolower($charset) == 'utf-8') {
$n = $tn = $noc = 0;
while ($n < strlen($string)) {
$t = ord($string[$n]); //ASCIIֵ
if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1; $n++; $noc++;
} elseif (194 <= $t && $t <= 223) {
$tn = 2; $n += 2; $noc += 2;
} elseif (224 <= $t && $t < 239) {
$tn = 3; $n += 3; $noc += 2;
} elseif (240 <= $t && $t <= 247) {
$tn = 4; $n += 4; $noc += 2;
} elseif (248 <= $t && $t <= 251) {
$tn = 5; $n += 5; $noc += 2;
} elseif ($t == 252 || $t == 253) {
$tn = 6; $n += 6; $noc += 2;
} else {
$n++;
}
if($noc >= $length) {
break;
}
}
if ($noc > $length) {
$n -= $tn;
}
$strcut = substr($string, 0, $n);
} else {
for ($i = 0; $i < $length; $i++) {
$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
}
}
$strcut = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $strcut);
return $strcut.$dot;
}
标签:php,截取字符串函数


猜你喜欢
Golang如何实现任意进制转换的方法示例
2024-02-23 07:43:48
教你如何在SQL Server计算机列和平均值
2009-01-20 15:10:00
MySQL高并发生成唯一订单号的方法实现
2024-01-28 00:27:38

使用PyCharm调试程序实现过程
2023-09-30 10:27:08

Select count(*)、Count(1)和Count(列)的区别及执行方式
2024-01-28 14:43:04

css基础教程属性篇
2008-07-23 12:44:00

Mybatis的where标签使用总结梳理
2024-01-17 01:56:18
不受欢迎的“欢迎页”
2008-04-20 16:41:00
如何更优雅地写python代码
2022-03-03 04:53:24
Python使用Selenium爬取淘宝异步加载的数据方法
2021-05-17 05:31:57
Python编写百度贴吧的简单爬虫
2023-12-06 02:17:56
快速一键生成Python爬虫请求头
2022-05-21 01:00:53

Python对比校验神器deepdiff库使用详解
2023-05-14 11:05:35
vue-cli 引入jQuery,Bootstrap,popper的方法
2024-05-21 10:17:21
python实现百万答题自动百度搜索答案
2021-10-06 03:57:11

关于淘宝网导航几个让人不解的问题
2009-03-24 21:08:00

忘记ftp密码使用python ftplib库暴力破解密码的方法示例
2021-01-02 03:08:31
Python中list列表的一些进阶使用方法介绍
2023-12-24 10:31:47
python爬取网页版QQ空间,生成各类图表
2023-01-18 06:30:58

Python嵌入C/C++进行开发详解
2024-01-02 06:39:48