PHP Conference Japan 2024

str_split

(PHP 5, PHP 7, PHP 8)

str_split將字串轉換為陣列

描述

str_split(string $string, int $length = 1): array

將字串轉換為陣列。

參數

string

輸入字串。

length

區塊的最大長度。

回傳值

如果指定了可選的 length 參數,則返回的陣列將被分解為長度為 length 的區塊,除非字串不能平均分割,則最後一個區塊可能會較短。預設的 length1,表示每個區塊的大小將為一個位元組。

錯誤/例外

如果 length 小於 1,將會拋出 ValueError

變更日誌

版本 描述
8.2.0 如果 string 為空,現在會回傳一個空的 array。先前會回傳一個包含單一空字串的 array
8.0.0 如果 length 小於 1,現在會拋出 ValueError;先前,會引發 E_WARNING 等級的錯誤,並且函式會回傳 false

範例

範例 #1 str_split() 的使用範例

<?php

$str
= "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

?>

以上範例會輸出

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)

注意事項

注意:

當處理多位元組編碼的字串時,str_split() 將會分割成位元組,而不是字元。mb_str_split() 可以用來將字串分割成碼位。grapheme_str_split() 可以用來將字串分割成字形叢集。

另請參閱

新增註解

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

4
Julian
1 年前
函式 str_split() 並不「感知」單字。以下是 str_split() 的改編版本,可以「感知」單字。

<?php

$array
= str_split_word_aware(
'In the beginning God created the heaven and the earth. And the earth was without form, and void; and darkness was upon the face of the deep.',
32
);

var_dump($array);

/**
* 這個函式與 str_split() 類似,但此函式會保持單字完整;它永遠不會分割單字。
*
* @return array<int, string>
*/
function str_split_word_aware(string $string, int $maxLengthOfLine): array
{
if (
$maxLengthOfLine <= 0) {
throw new
RuntimeException(sprintf('函式 %s() 的最大行長度必須大於一', __FUNCTION__));
}

$lines = [];
$words = explode(' ', $string);

$currentLine = '';
$lineAccumulator = '';
foreach (
$words as $currentWord) {

$currentWordWithSpace = sprintf('%s ', $currentWord);
$lineAccumulator .= $currentWordWithSpace;
if (
strlen($lineAccumulator) < $maxLengthOfLine) {
$currentLine = $lineAccumulator;
continue;
}

$lines[] = $currentLine;

// 使用目前的單字覆寫目前行和累加器
$currentLine = $currentWordWithSpace;
$lineAccumulator = $currentWordWithSpace;
}

if (
$currentLine !== '') {
$lines[] = $currentLine;
}

return
$lines;
}

?>

輸出

<?php

array(5) {
[
0]=> string(29) "In the beginning God created "
[1]=> string(30) "the heaven and the earth. And "
[2]=> string(28) "the earth was without form, "
[3]=> string(27) "and void; and darkness was "
[4]=> string(27) "upon the face of the deep. "
}

?>
To Top