(Practical) Multiple PHP Chinese string interception functions

黄舟
Release: 2023-03-05 12:42:01
Original
834 people have browsed it

字符串截取是一个非常常见的编程任务,而往往带中文的字符串截取会经常用到。虽然不难,但是自己写函数实现又耗费时间,这里介绍一个比较好用的字符串截取函数,能够胜任基本的需求了

=224 ) { $stringTMP = substr($string,$i,3); $i = $i + 3; } elseif( ord($stringTMP) >=192 ) { $stringTMP = substr($string,$i,2); $i = $i + 2; } else { $i = $i + 1; } $stringLast[] = $stringTMP; } $stringLast = implode("",$stringLast); if($append) { $stringLast .= "..."; } return $stringLast; } } $string = "简明现代魔法 —— 专注于互联网主流的各种技术"; $length = "27"; $append = true; echo sysSubStr($string,$length,$append); // 输出 // 简明现代魔法 —— 专... ?>
Copy after login

截取GB2312中文字符串:

 0xa0) { $tmpstr .= substr($str, $i, 2); $i++; } else $tmpstr .= substr($str, $i, 1); } return $tmpstr; } ?>
Copy after login

截取utf8编码的多字节字符串:

Copy after login

UTF-8、GB2312都支持的汉字截取函数:

 $sublen) return join('', array_slice($t_string[0], $start, $sublen))."..."; return join('', array_slice($t_string[0], $start, $sublen)); } else { $start = $start*2; $sublen = $sublen*2; $strlen = strlen($string); $tmpstr = ''; for($i=0; $i< $strlen; $i++) { if($i>=$start && $i< ($start+$sublen)) { if(ord(substr($string, $i, 1))>129) { $tmpstr.= substr($string, $i, 2); } else { $tmpstr.= substr($string, $i, 1); } } if(ord(substr($string, $i, 1))>129) $i++; } if(strlen($tmpstr)< $strlen ) $tmpstr.= "..."; return $tmpstr; } } $str = "abcd需要截取的字符串"; echo cut_str($str, 8, 0, 'gb2312'); ?>
Copy after login

以上就是(实用篇)多个PHP中文字符串截取函数的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


Related labels:
php
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!