2024 年日本 PHP 研討會

mb_str_split

(PHP 7 >= 7.4.0, PHP 8)

mb_str_split將多位元組字串轉換為其字元陣列

說明

mb_str_split(字串 $string, 整數 $length = 1, ?字串 $encoding = null): 陣列

此函數會返回一個字串陣列,它是 str_split() 的版本,支援可變字符大小的編碼以及 1、2 或 4 位元組字符的固定大小編碼。如果指定了 length 參數,則字串會被分解成指定長度(以字符為單位,而不是位元組)的區塊。可以選擇性地指定 encoding 參數,而且這樣做是一個良好的做法。

參數

string(字串)

要分割成字符或區塊的 字串

length(長度)

如果指定,返回陣列的每個元素將由多個字符組成,而不是單個字符。

encoding(編碼)

encoding 參數是字符編碼。如果省略或為 null,則將使用內部字符編碼值。

指定 支援的編碼 之一的字串。

返回值

mb_str_split() 返回一個字串陣列。

更新日誌

版本 說明
8.0.0 encoding 現在可以為 null。
8.0.0 此函數在失敗時不再返回 false

另請參閱

新增註解

使用者貢獻的註解 2 則註解

info at ensostudio dot ru
4 年前
注意:如果無法轉換參數類型,函數會返回 NULL。

基於套件 "symfony/polyfill-mbstring" 的 PHP < 7.4 polyfill
<?php
function mb_str_split($string, $split_length = 1, $encoding = null)
{
if (
null !== $string && !\is_scalar($string) && !(\is_object($string) && \method_exists($string, '__toString'))) {
trigger_error('mb_str_split(): expects parameter 1 to be string, '.\gettype($string).' given', E_USER_WARNING);
return
null;
}
if (
null !== $split_length && !\is_bool($split_length) && !\is_numeric($split_length)) {
trigger_error('mb_str_split(): expects parameter 2 to be int, '.\gettype($split_length).' given', E_USER_WARNING);
return
null;
}
$split_length = (int) $split_length;
if (
1 > $split_length) {
trigger_error('mb_str_split(): The length of each segment must be greater than zero', E_USER_WARNING);
return
false;
}
if (
null === $encoding) {
$encoding = mb_internal_encoding();
} else {
$encoding = (string) $encoding;
}

if (!
in_array($encoding, mb_list_encodings(), true)) {
static
$aliases;
if (
$aliases === null) {
$aliases = [];
foreach (
mb_list_encodings() as $encoding) {
$encoding_aliases = mb_encoding_aliases($encoding);
if (
$encoding_aliases) {
foreach (
$encoding_aliases as $alias) {
$aliases[] = $alias;
}
}
}
}
if (!
in_array($encoding, $aliases, true)) {
trigger_error('mb_str_split(): Unknown encoding "'.$encoding.'"', E_USER_WARNING);
return
null;
}
}

$result = [];
$length = mb_strlen($string, $encoding);
for (
$i = 0; $i < $length; $i += $split_length) {
$result[] = mb_substr($string, $i, $split_length, $encoding);
}
return
$result;
}
?>
webmaster at redinfo dot co dot kr
2 年前
if( !function_exists('mb_str_split')){
function mb_str_split( $string = '', $length = 1 , $encoding = null ){
if(!empty($string)){
$split = array();
$mb_strlen = mb_strlen($string,$encoding);
for($pi = 0; $pi < $mb_strlen; $pi += $length){
$substr = mb_substr($string, $pi,$length,$encoding);
if( !empty($substr)){
$split[] = $substr;
}
}
}
返回 $split;
}
}
To Top