在網上查了不少字符串分割方法,都沒法正確對UTF8字符串進行正確分割返回單個字符的數組。通過對FTU8編碼的分析寫出了下面的方法對UTF8進行分割。本人測試可用。本方法只支持UTF8編碼的,其它編碼轉自行轉換成UT8再使用。php
$tempaddtext="http://www.jishubu.net php對UTF8字體串進行單字分割返回數組";
//$tempaddtext=iconv("GBK","UTF-8",$tempaddtext); //字符編碼轉換,自行斷定須要不須要
$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);
返回結果:數組
Array ( [0] => h [1] => t [2] => t [3] => p [4] => : [5] => / [6] => / [7] => w [8] => w [9] => w [10] => . [11] => j [12] => i [13] => s [14] => h [15] => u [16] => b [17] => u [18] => . [19] => n [20] => e [21] => t [22] => p [23] => h [24] => p [25] => 對 [26] => U [27] => T [28] => F [29] => 8 [30] => 字 [31] => 體 [32] => 串 [33] => 進 [34] => 行 [35] => 單 [36] => 字 [37] => 分 [38] => 割 [39] => 返 [40] => 回 [41] => 數 [42] => 組 )