Разделить строку по пробелу php

Cтроку в массив по разделителю в PHP: explode, str_split, strtok — что выбрать?

Для того, чтобы преобразовать строку в массив по разделителю, можно использовать функцию explode()
Необходимые параметры: разделитель и строка.

// Пример 1 $pizza = "кусок1 кусок2 кусок3 кусок4 кусок5 кусок6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // кусок1 echo $pieces[1]; // кусок2 // Пример 2 $data = "foo:*:1023:1000::/home/foo:/bin/sh"; list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data); echo $user; // foo echo $pass; // *

2. preg_split: разбить строку на массив по регулярному выражению

Если возможностей explode() недостаточно, то можно использовать более мощную функцию: preg_split(). Она позволяет разбить строку не по фиксированному набору символов, а по регулярному выражению.

// разбиваем строку по произвольному числу запятых и пробельных символов, // которые включают в себя " ", \r, \t, \n и \f $keywords = preg_split("/[\s,]+/", "hypertext language, programming"); print_r($keywords);
/* Array ( [0] => hypertext [1] => language [2] => programming ) */

Преобразовать строку в массив по количеству символов

Функция str_split() преобразует строку в массив, разбивая ее на элементы с заданным количеством символов. Хотите узнать как ее использовать? Посмотрите документацию.

$str = "Hello Friend"; $arr2 = str_split($str, 3); print_r($arr2)
Array ( [0] => Hel [1] => lo [2] => Fri [3] => end )

Функция strtok(): разбиение строки на токены

Есть еще функция strtok() . Она позволит задать набор из нескольких символов-разделителей, для разделения строки по словам: читать подробнее про strok.

Читайте также:  Результат целочисленного деления java

Источник

explode

Возвращает массив строк, полученных разбиением строки string с использованием delimiter в качестве разделителя.

Список параметров

Если аргумент limit является положительным, возвращаемый массив будет содержать максимум limit элементов, при этом последний элемент будет содержать остаток строки string .

Если параметр limit отрицателен, то будут возвращены все компоненты кроме последних — limit .

Если limit равен нулю, то он расценивается как 1.

Замечание:

По историческим причинам, функции implode() можно передавать аргументы в любом порядке, но для explode() это недопустимо. Убедитесь в том, что delimiter указан перед аргументом string .

Возвращаемые значения

Возвращает массив ( array ) строк ( string ), созданный делением параметра string по границам, указанным параметром delimiter .

Если delimiter является пустой строкой («»), explode() возвращает FALSE . Если delimiter не содержится в string , и используется отрицательный limit , то будет возвращен пустой массив ( array ), иначе будет возвращен массив, содержащий string .

Список изменений

Версия Описание
5.1.0 Добавлена поддержка отрицательных значений limit

Примеры

Пример #1 Пример использования explode()

// Пример 1
$pizza = «кусок1 кусок2 кусок3 кусок4 кусок5 кусок6» ;
$pieces = explode ( » » , $pizza );
echo $pieces [ 0 ]; // кусок1
echo $pieces [ 1 ]; // кусок2

// Пример 2
$data = «foo:*:1023:1000::/home/foo:/bin/sh» ;
list( $user , $pass , $uid , $gid , $gecos , $home , $shell ) = explode ( «:» , $data );
echo $user ; // foo
echo $pass ; // *

Пример #2 Пример возвращаемого значения explode()

/*
Строка, которая не содержит разделителя, будет
просто возвращать массив с одним значением оригинальной строки.
*/
$input1 = «hello» ;
$input2 = «hello,there» ;
var_dump ( explode ( ‘,’ , $input1 ) );
var_dump ( explode ( ‘,’ , $input2 ) );

Результат выполнения данного примера:

array(1) ( [0] => string(5) "hello" ) array(2) ( [0] => string(5) "hello" [1] => string(5) "there" )

Пример #3 Примеры с использованием параметра limit

// положительный лимит
print_r ( explode ( ‘|’ , $str , 2 ));

// отрицательный лимит (начиная с PHP 5.1)
print_r ( explode ( ‘|’ , $str , — 1 ));
?>

Результат выполнения данного примера:

Array ( [0] => один [1] => два|три|четыре ) Array ( [0] => один [1] => два [2] => три )

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • preg_split() — Разбивает строку по регулярному выражению
  • str_split() — Преобразует строку в массив
  • mb_split() — Разделение строк в многобайтных кодировках, используя регулярное выражение
  • str_word_count() — Возвращает информацию о словах, входящих в строку
  • strtok() — Разбивает строку на токены
  • implode() — Объединяет элементы массива в строку

Источник

str_split

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()

$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

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. »
>

Источник

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

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

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];

Источник

Оцените статью