php分隔字串為數組

來源:互聯網
上載者:User

標籤: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分隔字串為數組

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.