文章总结了一种比较好的UTF8中文字符截断程序实例分享给大家参考。
最简单的字符截取函数是用php自带的substr()
其实,PHP原生就有多charset下字符截取方案,额,所以就是这个样子...??.
Multibyte String Functions函数族中,
string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] ) 用来字符串截取
int mb_strlen ( string $str [, string $encoding ] ) 返回字符串长度
但它只支持数字与字母不支持中文
实例
UTF8中文字符截断
代码如下 | 复制代码 |
/* UTF-8中文字符截断程序 */ $str = "123这是测试字符串"; $str1 = "()()"; echo subUTF8str($str,0,3)." "; echo subUTF8str($str,0,4)." "; echo subUTF8str($str1,0,4)." "; echo subUTF8str($str1,0,10)." "; function subUTF8str($str,$start=0,$length=80){ $cur_len = 0; //人理解的字符串长度 $all_len = strlen($str); //机器理解字符串长度 if($length > $all_len) { return $str; } for($i = 0;$i { if($cur_len == $start) { break; } if (ord($str[$i]) > 127) { $i += 3; }else{ $i += 1; } $cur_len ++; } $start_pos = $i; $temp_pos = $cur_len; for(;$cur_len - $temp_pos { if($i >= $all_len) break; if (ord($str[$i]) > 127) { $i += 3; }else{ $i += 1; } $cur_len ++; } $end_pos = $i; return substr($str,$start_pos,$end_pos); } ?> |
改进后我们把它分页,这样可支持ut8与gbk等中文字符截取
代码如下 | 复制代码 |
function substrs($content, $length){ function utf8_trim($str) { |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use
