PHP 8.4.2 Released!

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() 将字符串拆分为码点。

参见

添加备注

用户贡献的备注 1 note

up
4
Julian
1 year ago
The function str_split() is not 'aware' of words. Here is an adaptation of str_split() that is 'word-aware'.

<?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);

/**
* This function is similar to str_split() but this function keeps words intact; it never splits through a word.
*
* @return array<int, string>
*/
function str_split_word_aware(string $string, int $maxLengthOfLine): array
{
if (
$maxLengthOfLine <= 0) {
throw new
RuntimeException(sprintf('The function %s() must have a max length of line at least greater than one', __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;

// Overwrite the current line and accumulator with the current word
$currentLine = $currentWordWithSpace;
$lineAccumulator = $currentWordWithSpace;
}

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

return
$lines;
}

?>

OUTPUT:

<?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