str_split
(PHP 5)
str_split — Преобразует строку в массив
Описание
Преобразует строку в массив. Если указан необязательный аргумент split_length , возвращаемый массив будет содержать части исходной строки длиной split_length каждая, иначе каждый элемент будет содержать один символ.
Если split_length меньше 1, возвращается FALSE. Если split_length больше длины строки string , вся строка будет возвращена в первом и единственном элементе массива.
Пример #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 )
См. также описание функций chunk_split(), preg_split(), split(), count_chars() и str_word_count(), а также for.
- addcslashes
- addslashes
- bin2hex
- chop
- chr
- chunk_split
- convert_cyr_string
- convert_uudecode
- convert_uuencode
- count_chars
- crc32
- crypt
- echo
- explode
- fprintf
- get_html_translation_table
- hebrev
- hebrevc
- hex2bin
- html_entity_decode
- htmlentities
- htmlspecialchars_decode
- htmlspecialchars
- implode
- join
- lcfirst
- levenshtein
- localeconv
- ltrim
- md5_file
- md5
- metaphone
- money_format
- nl_langinfo
- nl2br
- number_format
- ord
- parse_str
- printf
- quoted_printable_decode
- quoted_printable_encode
- quotemeta
- rtrim
- setlocale
- sha1_file
- sha1
- similar_text
- soundex
- sprintf
- sscanf
- str_getcsv
- str_ireplace
- str_pad
- str_repeat
- str_replace
- str_rot13
- str_shuffle
- str_split
- str_word_count
- strcasecmp
- strchr
- strcmp
- strcoll
- strcspn
- strip_tags
- stripcslashes
- stripos
- stripslashes
- stristr
- strlen
- strnatcasecmp
- strnatcmp
- strncasecmp
- strncmp
- strpbrk
- strpos
- strrchr
- strrev
- strripos
- strrpos
- strspn
- strstr
- strtok
- strtolower
- strtoupper
- strtr
- substr_compare
- substr_count
- substr_replace
- substr
- trim
- ucfirst
- ucwords
- vfprintf
- vprintf
- vsprintf
- wordwrap
Коментарии
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. "
}
?>