php分割中文字符串为数组的简单例子

近日在做东西时,遇到要把中文字符进行逐字分割,试了很多方法,都不行,后来发现了一个超简单的方法:

分割字符串很简单,主要是用到函数preg_match_all。
当处理含有中文的字符串时,可以用如下的方法:

 
  1. <?php  
  2.     $str = "hi钓鱼岛是中国的";  
  3.     preg_match_all("/./u", $str, $arr);  
  4.     print_r($arr[0]);  
  5.     //by www.jbxue.com  
  6. ?>  

输出结果:
Array
(
[0] => h
[1] => i
[2] => 钓
[3] => 鱼
[4] => 岛
[5] => 是
[6] => 中
[7] => 国
[8] => 的
)

说明:模式修饰符u在php5中已完全支持。

例2,PHP分割中文字符串

将字符串“爱莲说”分割为“爱”,“莲”,“说”单个字。

使用到php函数preg_match_all。
示例:

 
  1. <?php  
  2. $str = "爱莲说";  
  3. preg_match_all('/[x{4e00}-x{9fa5}]/u',$str,$string);  
  4. dump($string);  
  5. //by www.jbxue.com  
  6. ?>  

输出结果:
 array
 0=>
 array
 0 =>string '爱'(length=3)
 1 =>string'莲'(length=3)
 2 =>string '说'(length=3)
这时,获取具体的某个字,即可通过数组获取。

有关使用php分割中英文字符串的方法,可以参考文章:php分割中英文字符串的几种方法

原文:http://www.jbxue.com/article/9999.html

(转载请注明花儿为何那样红博客)
原文地址:https://www.cnblogs.com/chancy/p/6941357.html