PHP分割汉字为数组


<?php
$string ="帅朱好cc变c态啊,2!";
$arr1 = str_split_utf8($string,'gbk');
var_dump($arr1);

/**
 * 将汉字字符串分割为数组
 *
 * @param string $str
 * @param string $charset 字符编码 默认gbk
 * @return Array
 */
function str_split_utf8($str,$charset='gbk') {
    $str = iconv($charset,'utf-8',$str);
    $split=1;
    $array = array();
    for ( $i=0; $i < strlen( $str ); ){
        $value = ord($str[$i]);
        if($value > 127){
            if($value >= 192 && $value <= 223)
            $split=2;
            elseif($value >= 224 && $value <= 239)
            $split=3;
            elseif($value >= 240 && $value <= 247)
            $split=4;
        }else{
            $split=1;
        }
        $key = NULL;
        for ( $j = 0; $j < $split; $j++, $i++ ) {
            $key .= $str[$i];
        }
        array_push( $array, $key );
    }

    foreach($array as $key=>$value)
    {
        $array[$key] = iconv('utf-8',$charset,$value);
    }
    return $array;
}

 

结果:

标签: ,

关于 虫少侠