Home  >  Article  >  Backend Development  >  将中文字符串分割为数组 解决str_split中文乱码php

将中文字符串分割为数组 解决str_split中文乱码php

不言
不言Original
2018-05-24 14:30:433684browse

首先来介绍str_split()这个函数;

它的作用是将字符串分割为数组;

例如:

$str='abcde';
str_plite($str);
打印结果如下:
Array(    [0] => a    [1] => b    [2] => c    [3] => d    [4] => e)

看似很好用的样子;但是作为中国程序员;不可避免的要和中文打交道;

这时候再用str_splite就会悲剧的发现乱码了;;;

不要怕;preg_splite可以拯救这个问题;

当然是需要配合正则使用的;

/** 
* 将字符串分割为数组     
* @param  string $str 字符串 
* @return array       分割得到的数组 
*/
function mb_str_split($str){    
return preg_split(&#39;/(?<!^)(?!$)/u&#39;, $str );
}
$str=&#39;白俊遥博客&#39;;
mb_str_split($str);
打印结果如下:
Array(    [0] => 白    [1] => 俊    [2] => 遥    [3] => 博    [4] => 客)

打完;收工;

Statement:
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