3weq 发表于 2014-7-8 09:01:56

php对UTF8字体串进行单字分割返回数组

在网上查了很多字符串分割方法,都无法正确对UTF8字符串进行正确分割返回单个字符的数组。经过对FTU8编码的分析写出了下面的方法对UTF8进行分割。本人测试可用。本方法只支持UTF8编码的,其它编码转自行转换成UT8再使用。

   
$tempaddtext="http://www.yunvn.com php对UTF8字体串进行单字分割返回数组";
<br>//$tempaddtext=iconv("GBK","UTF-8",$tempaddtext); //字符编码转换,自行判定需要不需要 <br>
$cind = 0;
$arr_cont = array();
for ($i = 0; $i < strlen($tempaddtext); $i++) {
         if (strlen(substr($tempaddtext, $cind, 1)) > 0) {
               if (ord(substr($tempaddtext, $cind, 1)) < 192) {
                   if (substr($tempaddtext, $cind, 1) != " ") {
                     array_push($arr_cont, substr($tempaddtext, $cind, 1));
                   }
                   $cind++;
               } elseif(ord(substr($tempaddtext, $cind, 1)) < 224) {
                   array_push($arr_cont, substr($tempaddtext, $cind, 2));
                   $cind+=2;
               } else {
                   array_push($arr_cont, substr($tempaddtext, $cind, 3));
                   $cind+=3;
               }
         }
       }
   
      print_r($arr_cont);

  返回结果:
1
   
Array ( => h => t => t => p => : => / => / => w => w => w => . => j => i => s => h => u => b => u => . => n => e => t => p => h => p => 对 => U => T => F => 8 => 字 => 体 => 串 => 进 => 行 => 单 => 字 => 分 => 割 => 返 => 回 => 数 => 组 )

  
页: [1]
查看完整版本: php对UTF8字体串进行单字分割返回数组