str_split
(PHP 5, PHP 7, PHP 8)
str_split — 将字符串转换为数组
参数
string
-
输入字符串。
length
-
每一段的长度。
返回值
如果指定了可选的 length
参数,返回数组中的每个元素长度均为 length
的块,除了最后一个块,如果字符串不是均匀划分,则可能会更短。默认 length
是
1
,这意味着每个块的大小是一个字节。
错误/异常
如果 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() 可用于将字符串拆分为字素簇。
参见
- mb_str_split() - 指定多字节字符串,返回其字符数组
- grapheme_str_split() - Split a string into an array
- chunk_split() - 将字符串分割成小块
- preg_split() - 通过一个正则表达式分隔字符串
- explode() - 使用一个字符串分割另一个字符串
- count_chars() - 返回字符串所用字符的信息
- str_word_count() - 返回字符串中单词的使用情况
- for
+添加备注
用户贡献的备注 1 note
Julian ¶
2 years 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. "
}
?>