PHP截取中文字符串,无乱码,基于正则
Jun 06, 2016 pm 07:35 PM
p
php
Chinese
Garbled characters
based on
string
intercept
regular
多数网上的PHP中文字符串截取,计算长度用的是逐个字符遍历的方法,看起来比较复杂 这里提供哦你一种基于正则的解决方案,GBK,UTF-8的中文字符串测试通过 无 ?php/** * @brief strlen_mb 计算字符串长度,支持中文,自动检测编码,UTF-8与GBK测试通过 * * @p
多数网上的PHP中文字符串截取,计算长度用的是逐个字符遍历的方法,看起来比较复杂
这里提供哦你一种基于正则的解决方案,GBK,UTF-8的中文字符串测试通过
<?php /** * @brief strlen_mb 计算字符串长度,支持中文,自动检测编码,UTF-8与GBK测试通过 * * @param $str * * @return */ function strlen_mb($str){ $mb_len = mb_detect_encoding($str) == 'UTF-8' ? 2 : 1; $patt = '/([\x00-\x7f]|[\x80-\xff].{' . $mb_len . '})/'; $match = preg_match_all($patt, $str, $groups); if($groups){ return count($groups[0]); }else{ return false; } } /** * @brief substr_mb 截取字符串,中文防乱码,自动检测编码,UTF-8与GBK测试通过 * * @param $str * @param $start * @param $len * * @return */ function substr_mb($str, $start, $len){ $mb_len = mb_detect_encoding($str) == 'UTF-8' ? 2 : 1; $patt = '/([\x00-\x7f]|[\x80-\xff].{' . $mb_len . '}){' . $len . '}/'; preg_match($patt, $str, $groups); if($groups){ return $groups[0]; }else{ return false; } } echo '<meta charset=utf-8>'; $str = '北京dd欢迎你'; for($i = 0; $i <= strlen_mb($str); $i++){ var_dump(substr_mb($str, 0, $i)); }
Copy after login
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

Hot Article
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot tools Tags

Hot Article
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot Article Tags

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

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

How To Set Up Visual Studio Code (VS Code) for PHP Development
