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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

In this chapter, we are going to learn the following topics related to routing ?

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Validator can be created by adding the following two lines in the controller.
