php字符串截取,支持中文和其他编码
本文章总结了在php函数substr的基础上来截取字符串的函数,但在碰到中文时出现汉字截取一半出现乱码的解决办法了,下面介绍了支持中文和其他编码截取程序。
代码如下 | 复制代码 |
/** |
如果我们直接使用了php substr来截取数据如
在英文和汉字混合的情况下会出现如下问题:
如果有这样一个字符串
$str="这是一个字符串";
为了截取该串的前10个字符,使用
if(strlen($str)>10) $str=substr($str,10)."…";
那么,echo $str的输出应该是"这是一个字…"
假设
$str="这是1个字符串";
这个串中包含了一个半角字符,同样执行:
if(strlen($str)>10) $str=substr($str,10);
由于原字符串$str的第10、11个字符构成了汉字“符”;
执行串分割后会将该汉字一分为二,这样被截取的串就会发现乱码现象
使用了上面这代码字符截取代码就可以方便的解决了这种问题了。
今天找到一个比较好的截取中文字符串方法,在此与大家共享。
代码如下 | 复制代码 |
function msubstr($str, $start, $len) { |
程序二:PHP截取UTF-8字符串,解决半字符问题
/******************************************************************
* PHP截取UTF-8字符串,解决半字符问题。
* 英文、数字(半角)为1字节(8位),中文(全角)为3字节
* @return 取出的字符串, 当$len小于等于0时, 会返回整个字符串
* @param $str 源字符串
* $len 左边的子串的长度
****************************************************************/
代码如下 | 复制代码 |
function utf_substr($str,$len) { for($i=0;$i{ $temp_str=substr($str,0,1); if(ord($temp_str) > 127) { $i++; if($i{ $new_str[]=substr($str,0,3); $str=substr($str,3); } } else { $new_str[]=substr($str,0,1); $str=substr($str,1); } } return join($new_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),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
