(PHP 5, PHP 7, PHP
str_split — Convert a string to an array
Description
str_split(string $string
, int $length
= 1): array
Parameters
-
string
-
The input string.
-
length
-
Maximum length of the chunk.
Return Values
If the optional length
parameter is
specified, the returned array will be broken down into chunks with each
being length
in length, except the final chunk
which may be shorter if the string does not divide evenly. The default
length
is 1
, meaning every chunk will be one byte in size.
Errors/Exceptions
If length
is less than 1
,
a ValueError will be thrown.
Changelog
Version | Description |
---|---|
8.2.0 |
If string is empty an empty array is now returned.Previously an array containing a single empty string was returned. |
8.0.0 |
If length is less than 1 ,a ValueError will be thrown now; previously, an error of level E_WARNING has been raised instead, and the function returned false .
|
Examples
Example #1 Example uses of str_split()
<?php
$str
= "Hello Friend";$arr1 = str_split($str);
$arr2 = str_split($str, 3);print_r($arr1);
print_r($arr2);?>
The above example will output:
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 )
Notes
Note:
str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string.
Use mb_str_split() to split the string into code points.
See Also
- mb_str_split() — Given a multibyte string, return an array of its characters
- chunk_split() — Split a string into smaller chunks
- preg_split() — Split string by a regular expression
- explode() — Split a string by a string
- count_chars() — Return information about characters used in a string
- str_word_count() — Return information about words used in a string
- for
Julian ¶
2 months 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:
<?phparray(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. "
}?>
alex-glebe at mail dot ru ¶
3 months ago
Empty string Does'n returns Empty array!
$arr0 = str_split("");
print_r($arr0);
Array
(
[0] =>
)
lskatz at gmail dot com ¶
14 years ago
A good use of str_split is reverse translating an amino acid sequence.
<?php
/* reverse translate an aa sequence using its dna counterpart */
function reverseTranslate($aaSeq,$ntSeq){
$nt=str_split($ntSeq,3);
$aa=str_split($aaSeq,1);
$gapChar=array('*','-');
$numAa=count($aa);
$ntIndex=0;
$newNtSeq="";
for($i=0;$i<$numAa;$i++){
// if the aa is a gap, then just put on a gap character
if(in_array($aa[$i],$gapChar)){
$newNtSeq.='---';
}
else{
$newNtSeq.=$nt[$ntIndex];
$ntIndex++;
}
}
return $newNtSeq;
}
?>
str_split
(PHP 5, PHP 7)
str_split — Преобразует строку в массив
Описание
array str_split
( string $string
[, int $split_length
= 1
] )
Список параметров
-
string
-
Входная строка.
-
split_length
-
Максимальная длина фрагмента.
Возвращаемые значения
Если указан необязательный аргумент 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 )
Примечания
Замечание:
Функция str_split() производит разбивку по байтам,
а не по символам, в случае использования строк в многобайтных кодировках.
Смотрите также
- chunk_split() — Разбивает строку на фрагменты
- preg_split() — Разбивает строку по регулярному выражению
- explode() — Разбивает строку с помощью разделителя
- count_chars() — Возвращает информацию о символах, входящих в строку
- str_word_count() — Возвращает информацию о словах, входящих в строку
- for
Вернуться к: Обработка строк
Depending on your full requirements and if you need the string array unmodified too, you could use explode
for this, something like this would get your words into an array:
$str = "hey hello man are you going to write some code";
$str_arr = explode(' ', $str);
Then you can use array_filter
to remove the words you don’t want, like so:
function min4char($word) {
return strlen($word) >= 4;
}
$final_str_array = array_filter($str_arr, 'min4char');
Otherwise if you don’t need the unmodified array, you can use a regular expression to get all matches that are above a certain length using preg_match_all
, or replace out the ones that are using preg_replace
.
One final option would be to do it the basic way, use explode
to get your array as per the first code example, and then loop over everything using unset
to remove the entry from the array. But then, you’d also need to reindex (depending on your subsequent usage of the ‘fixed’ array), which could be inefficient depending on how large your array is.
EDIT: Not sure why there are claims that it does not work, see below for output of var_dump($final_str_array)
:
array(5) { [1]=> string(5) "hello" [5]=> string(5) "going" [7]=> string(5) "write" [8]=> string(4) "some" [9]=> string(4) "code" }
@OP, to convert this back to your string, you can simply call implode(' ', $final_str_array)
to get this output:
hello going write some code
Примеры преобразования строк текста в массив по разным разделителям.
1
Разделить текст по переносам строк
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Proin blandit magna eu tempus ullamcorper.
Sed porta justo sed nibh elementum condimentum.
Quisque non eros sit amet elit commodo maximus eget a eros.";
$array = explode("n", $text);
print_r($array);
PHP
Результат:
Array
(
[0] => Lorem ipsum dolor sit amet, consectetur adipiscing elit.
[1] => Proin blandit magna eu tempus ullamcorper.
[2] => Sed porta justo sed nibh elementum condimentum.
[3] => Quisque non eros sit amet elit commodo maximus eget a eros.
)
2
Разделить текст по предложениям
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin blandit
magna eu tempus ullamcorper! Sed porta justo sed nibh elementum condimentum.
Quisque non eros sit amet elit commodo maximus eget a eros?";
$text = str_replace("n", '', $text);
$array = preg_split('/(?<=[.?!])s+(?=[a-zа-яё])/i', $text);
print_r($array);
PHP
Результат:
Array
(
[0] => Lorem ipsum dolor sit amet, consectetur adipiscing elit.
[1] => Proin blandit magna eu tempus ullamcorper!
[2] => Sed porta justo sed nibh elementum condimentum.
[3] => Quisque non eros sit amet elit commodo maximus eget a eros?
)
3
Разделить текст по словам
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin blandit magna eu tempus ullamcorper.";
$text = preg_replace("/[^a-zа-яё0-9s]/i", '', $text);
$array = preg_split('/(s)/', $text);
$array = array_diff($array, array(''));
print_r($array);
PHP
Результат:
Array
(
[0] => Lorem
[1] => ipsum
[2] => dolor
[3] => sit
[4] => amet
[5] => consectetur
[6] => adipiscing
[7] => elit
[8] => Proin
[9] => blandit
[10] => magna
[11] => eu
[12] => tempus
[13] => ullamcorper
)
4
Разделить текст по буквам
$text = "Lorem ipsum dolor sit amet";
$array = str_split($text);
print_r($array);
PHP
Результат:
Array
(
[0] => L
[1] => o
[2] => r
[3] => e
[4] => m
[5] =>
[6] => i
[7] => p
[8] => s
[9] => u
[10] => m
[11] =>
[12] => d
[13] => o
[14] => l
[15] => o
[16] => r
[17] =>
[18] => s
[19] => i
[20] => t
[21] =>
[22] => a
[23] => m
[24] => e
[25] => t
)
5
Разделить текст по нескольким разделителям
Разделители -
и :
$text = "Lorem ipsum dolor sit amet-proin blandit magna eu:Sed porta justo.";
$array = preg_split('/[-|:]/u', $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($array);
PHP
Результат:
Array
(
[0] => Lorem ipsum dolor sit amet
[1] => proin blandit magna eu
[2] => Sed porta justo.
)
Если разделитель из нескольких символов, например <br>
и </br>
:
$text = "Lorem ipsum dolor sit amet,<br>proin blandit magna eu.</br>Sed porta justo.";
$array = preg_split('/(<br>)|(</br>)/u', $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($array);
PHP
Результат:
Array
(
[0] => Lorem ipsum dolor sit amet,
[1] => proin blandit magna eu.
[2] => Sed porta justo.
)
6
Разделить текст на равные части
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin blandit magna eu tempus ullamcorper.";
$chunks = 10;
$array = str_split($text);
$chunks = array_chunk($array, $chunks, false);
$result = array();
foreach ($chunks as $chunk) {
$result[] = implode($chunk);
}
print_r($result);
PHP
Результат:
Array
(
[0] => Lorem ipsu
[1] => m dolor si
[2] => t amet, co
[3] => nsectetur
[4] => adipiscing
[5] => elit. Pro
[6] => in blandit
[7] => magna eu
[8] => tempus ull
[9] => amcorper.
)
27.12.2020, обновлено 05.04.2022
Другие публикации
Имеем несколько колонок с разным по длине текстом, нужно сделать их одинаковой высоты и скрыть лишнее.
Clipboard.js – мини плагин для копирования текста с сайта в буфер обмена, который не использует flash и JQuery.
Примеры, как вывести текст в три колонки одинаковой ширины и отступом между ними с помощью разных CSS-свойств.
В PHP за перенос текста отвечают управляющие символы r (возврат каретки) и n (перевод строки), причем в разных операционных системах (на которых работает сервер) они применяются в разных комбинациях.
Один из вариантов поиска похожих статей в базе данных основан на схождении слов в двух текстах.
Обзор PHP-функций для работы со строками и практическое их применение с учетом кодировки UTF-8.
By
/ February 20, 2022 February 20, 2022
WHAT IS THE SYNTAX OF THE STR_SPLIT()FUNCTION IN PHP?
str_split(string,length)
Parameter | Description |
---|---|
string | Required. Specifies the string to split |
length | Optional. Specifies the length of each array element. Default is 1 |
EXAMPLES OF THE STR_SPLIT() FUNCTION
Example 1. In this example, we split the string “Hello” into an array.
<?php
print_r(str_split("Hello"));
?>
Example 2. In this example, we use the length parameter.
<?php
print_r(str_split("Hello",3));
?>