標籤:reac 輸出 int convert 工作 turn enc div odi
工作中會經常分隔字串為數組,我們可以用php內建函數str_split(),可是有時候字串中包含中文,切割後會亂碼,比如
print_r(str_split(‘dw氛圍fesf‘,3));
輸出
Array( [0] => php [1] => ? [2] => ?? [3] => ?? [4] => ?? [5] => ?? [6] => ?!! [7] => !)
為了能處理多位元組字串
下面函數可以實現
function mbStringToArray($str) { if(empty($str)){ return false; } $len = mb_strlen($str); $array = array(); for($i = 0; $i<$len; $i++) { $array[] = mb_substr($str, $i, 1); } return $array;}/** * @param str $str * @param int $length 截取長度 * @param boole $byte 是否按位元組分隔 false 按字元數分隔 * @return array*/function _str_split($str,$length,$byte=false){ if(mb_strwidth($str) == 1 || empty($str)){ return $str; } if($encoding = mb_detect_encoding($str, null, true) === false ){ return str_split($str, $length); } $utf8_str = mb_convert_encoding($str, ‘utf8‘, $encoding); if($byte){ $line = ‘‘; $split_arr = []; foreach (preg_split(‘//u‘, $utf8_str,-1,PREG_SPLIT_NO_EMPTY ) as $char) { $width = mb_strwidth($line.$char,‘utf8‘); if($width <= $length){ $line .= $char; continue; } $split_arr[] = str_pad($line, $width); $line = $char; } return $split_arr; }else{ $str_arr = mbStringToArray($str); if($str_arr){ $chunk_index = 0; $k_index = 0; $line = ‘‘; $chunks = []; foreach ($str_arr as $key=>$val){ $line .= $val; $chunks[$k_index] = $line; if ($chunk_index++ == $length-1) { $line = ‘‘; $k_index++; $chunk_index = 0; } } } return $chunks; }}
執行
print_r(_str_split($str,3,false));
輸出
Array( [0] => php [1] => 開發 [2] => 者中心 [3] => !!!)
php分隔字串為數組