- Exploding by Array of Delimiters
- 6 Answers 6
- explode
- Parameters
- Return Values
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 3 notes
- str_split
- Ошибки
- Список изменений
- Примеры
- Примечания
- Смотрите также
- User Contributed Notes 3 notes
- Преобразование строк в массив PHP
- Разделить текст по переносам строк
- Результат:
- Разделить текст по предложениям
- Результат:
- Разделить текст по словам
- Результат:
- Разделить текст по буквам
- Результат:
- Разделить текст по нескольким разделителям
- Результат:
- Результат:
- Разделить текст на равные части
- Результат:
Exploding by Array of Delimiters
Instead of using string $delimiter is there any way to use array $delimiter without affecting performance too much?
6 Answers 6
$str = 'Monsters are SUPER scary, bro!'; $del = array('a', 'b', 'c'); // In one fell swoop. $arr = explode( $del[0], str_replace($del, $del[0], $str) );
After studying this page for much too long, I’m guessing 65Fbef05’s answer was changed to defeat the bug.
Use preg_split() with an appropriate regex.
For example: print_r(preg_split(«/[,. ]/», «0 1,2.3»)); will give you Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3) .
print_r(preg_split(«/[,\. ]/», «0 1,2.3»)); you mean 🙂 Thanks though, probably the best way I guess.
function explode_by_array($delim, $input) < $unidelim = $delim[0]; $step_01 = str_replace($delim, $unidelim, $input); //Extra step to create a uniform value return explode($unidelim, $step_01); >
That’s improved @65Fbef05’s code. We use first delimiter, because «+delim+» may be used in original string.
The above suggestions won’t work if the delimiters after the first delimiter include characters from that first delimiter. For instance, if you want to use line breaks as delimiters, but you’re not sure if your input uses \r\n, \r or just \n, you can’t use the above methods.
$str = '___RN___RN___R___N___RN___RN'; $del = array('RN', 'R', 'N'); # This won't work if delimiters 2, 3, n include characters from delimiter 1 var_dump(explode( $del[0], str_replace($del, $del[0], $str)));
array(11) < [0]=>string(4) "___R" [1]=> string(0) "" [2]=> string(4) "___R" [3]=> string(0) "" [4]=> string(4) "___R" [5]=> string(3) "___" [6]=> string(4) "___R" [7]=> string(0) "" [8]=> string(4) "___R" [9]=> string(0) "" [10]=> string(0) "" >
Which isn’t ideal if you’re planning to do string comparisons. Instead, you’ll need to get a bit more complex. What I have written below may not be the most efficient and succinct, but it does the trick.
# This, however, will work function array_explode($delimiters, $string) < if(!is_array(($delimiters)) && !is_array($string))< //if neither the delimiter nor the string are arrays return explode($delimiters,$string); >else if(!is_array($delimiters) && is_array($string)) < //if the delimiter is not an array but the string is foreach($string as $item)< foreach(explode($delimiters, $item) as $sub_item)< $items[] = $sub_item; >> return $items; > else if(is_array($delimiters) && !is_array($string)) < //if the delimiter is an array but the string is not $string_array[] = $string; foreach($delimiters as $delimiter)< $string_array = array_explode($delimiter, $string_array); >return $string_array; > > var_dump(array_explode($del,$str));
It will output the following:
array(7) < [0]=>string(3) "___" [1]=> string(3) "___" [2]=> string(3) "___" [3]=> string(3) "___" [4]=> string(3) "___" [5]=> string(3) "___" [6]=> string(0) "" >
explode
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator .
Parameters
If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string .
If the limit parameter is negative, all components except the last — limit are returned.
If the limit parameter is zero, then this is treated as 1.
Note:
Prior to PHP 8.0, implode() accepted its parameters in either order. explode() has never supported this: you must ensure that the separator argument comes before the string argument.
Return Values
Returns an array of string s created by splitting the string parameter on boundaries formed by the separator .
If separator is an empty string («»), explode() throws a ValueError . If separator contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned. If separator values appear at the start or end of string , said values will be added as an empty array value either in the first or last position of the returned array respectively.
Changelog
Version | Description |
---|---|
8.0.0 | explode() will now throw ValueError when separator parameter is given an empty string ( «» ). Previously, explode() returned false instead. |
Examples
Example #1 explode() examples
// Example 1
$pizza = «piece1 piece2 piece3 piece4 piece5 piece6» ;
$pieces = explode ( » » , $pizza );
echo $pieces [ 0 ]; // piece1
echo $pieces [ 1 ]; // piece2
?php
// Example 2
$data = «foo:*:1023:1000::/home/foo:/bin/sh» ;
list( $user , $pass , $uid , $gid , $gecos , $home , $shell ) = explode ( «:» , $data );
echo $user ; // foo
echo $pass ; // *
Example #2 explode() return examples
/*
A string that doesn’t contain the delimiter will simply
return a one-length array of the original string.
*/
$input1 = «hello» ;
$input2 = «hello,there» ;
$input3 = ‘,’ ;
var_dump ( explode ( ‘,’ , $input1 ) );
var_dump ( explode ( ‘,’ , $input2 ) );
var_dump ( explode ( ‘,’ , $input3 ) );
?php
The above example will output:
array(1) ( [0] => string(5) "hello" ) array(2) ( [0] => string(5) "hello" [1] => string(5) "there" ) array(2) ( [0] => string(0) "" [1] => string(0) "" )
Example #3 limit parameter examples
// positive limit
print_r ( explode ( ‘|’ , $str , 2 ));
// negative limit
print_r ( explode ( ‘|’ , $str , — 1 ));
?>
The above example will output:
Array ( [0] => one [1] => two|three|four ) Array ( [0] => one [1] => two [2] => three )
Notes
Note: This function is binary-safe.
See Also
- preg_split() — Split string by a regular expression
- str_split() — Convert a string to an array
- mb_split() — Split multibyte string using regular expression
- str_word_count() — Return information about words used in a string
- strtok() — Tokenize string
- implode() — Join array elements with a string
User Contributed Notes 3 notes
Note that an empty input string will still result in one element in the output array. This is something to remember when you are processing unknown input.
For example, maybe you are splitting part of a URI by forward slashes (like «articles/42/show» => [«articles», «42», «show»]). And maybe you expect that an empty URI will result in an empty array («» => []). Instead, it will contain one element, with an empty string:
$uri = » ;
$parts = explode ( ‘/’ , $uri );
var_dump ( $parts );
Be careful, while most non-alphanumeric data types as input strings return an array with an empty string when used with a valid separator, true returns an array with the string «1»!
var_dump(explode(‘,’, null)); //array(1) < [0]=>string(0) «» >
var_dump(explode(‘,’, false)); //array(1) < [0]=>string(0) «» >
var_dump(explode(‘,’, true)); //array(1) < [0]=>string(1) «1» >
If you want to directly take a specific value without having to store it in another variable, you can implement the following:
echo $status_only = explode(‘-‘, $status)[0];
str_split
Если указан необязательный параметр 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()
$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() , чтобы разбить строку на кодовые точки.
Смотрите также
- mb_str_split() — Если задана многобайтовая строка возвращает массив символов
- chunk_split() — Разбивает строку на фрагменты
- preg_split() — Разбивает строку по регулярному выражению
- explode() — Разбивает строку с помощью разделителя
- count_chars() — Возвращает информацию о символах, входящих в строку
- str_word_count() — Возвращает информацию о словах, входящих в строку
- for
User Contributed Notes 3 notes
The function str_split() is not ‘aware’ of words. Here is an adaptation of str_split() that is ‘word-aware’.
$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
);
/**
* This function is similar to str_split() but this function keeps words intact; it never splits through a word.
*
* @return array
*/
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;
>
// Overwrite the current line and accumulator with the current word
$currentLine = $currentWordWithSpace ;
$lineAccumulator = $currentWordWithSpace ;
>
if ( $currentLine !== » ) $lines [] = $currentLine ;
>
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. »
>
Преобразование строк в массив PHP
Примеры преобразования строк текста в массив по разным разделителям.
Разделить текст по переносам строк
$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);
Результат:
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. )
Разделить текст по предложениям
$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);
Результат:
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? )
Разделить текст по словам
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin blandit magna eu tempus ullamcorper."; $text = preg_replace("/[^a-zа-яё0-9\s]/i", '', $text); $array = preg_split('/(\s)/', $text); $array = array_diff($array, array('')); print_r($array);
Результат:
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 )
Разделить текст по буквам
$text = "Lorem ipsum dolor sit amet"; $array = str_split($text); print_r($array);
Результат:
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 )
Разделить текст по нескольким разделителям
$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);
Результат:
Array ( [0] => Lorem ipsum dolor sit amet [1] => proin blandit magna eu [2] => Sed porta justo. )
Если разделитель из нескольких символов, например
и :
$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);
Результат:
Array ( [0] => Lorem ipsum dolor sit amet, [1] => proin blandit magna eu. [2] => Sed porta justo. )
Разделить текст на равные части
$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);
Результат:
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. )