Php array functions explode

php explode

Summary: in this tutorial, you’ll learn how to use the PHP explode() function to split a string by a separator into an array of strings.

Introduction to the PHP explode() function

The PHP explode() function returns an array of strings by splitting a string by a separator. The following shows the syntax of the explode() function:

explode ( string $separator , string $string , int $limit = PHP_INT_MAX ) : arrayCode language: PHP (php)

The explode() function has the following parameters:

  • $separator is the delimiter that the explode() function uses to split the $string.
  • $string is the input string
  • $limit specifies how the function will return the result array.

If the $limit is positive, the explode() function returns an array with $limit elements where the last element containing the rest of the string.

If the $limit is zero, explode() function interprets it as one. So the function returns an array with the original string.

If the $limit is negative, the explode() function splits the $string using the $separator . Also, it removes the last $limit elements from the result array.

Prior to PHP 8.0.0, the explode() function returns false if the $separator is an empty string. Starting from PHP 8.0.0, the explode() function throws a ValueError instead.

PHP explode() function examples

Let’s take some examples of using the explode() function.

1) Simple the PHP explode() function example

The following example uses the explode() function to split a string by a comma ( , ):

 $str = 'first_name,last_name,email,phone'; $headers = explode(',', $str); print_r($headers);Code language: PHP (php)
array(4) < [0]=> string(10) "first_name" [1]=> string(9) "last_name" [2]=> string(5) "email" [3]=> string(5) "phone" >Code language: PHP (php)

2) Using the PHP explode() function with a positive $limit

The following example uses the explode() function with the a positive $limit argument:

$str = 'first_name,last_name,email,phone'; $headers = explode(',', $str, 3); var_dump($headers);Code language: PHP (php)
array(3) < [0]=> string(10) "first_name" [1]=> string(9) "last_name" [2]=> string(5) "email,phone" >Code language: PHP (php)

As shown clearly in the output, the returned array contains three elements specified by the $limit argument. Also, the last element has the remaining string.

3) Using the PHP explode() function with a negative $limit

The following example uses the explode() function with the a negative $limit argument:

$str = 'first_name,last_name,email,phone'; $headers = explode(',', $str, -1); var_dump($headers);Code language: PHP (php)
array(3) < [0]=> string(10) "first_name" [1]=> string(9) "last_name" [2]=> string(5) "email" >Code language: PHP (php)

In this example, the explode() function returns an array of the string split by the comma ( , ). Also, it excludes the last element from the result array.

If you use -2 instead of – 1 for the $limit , the explode() function will remove the last 2 elements. For example:

$str = 'first_name,last_name,email,phone'; $headers = explode(',', $str, -1); var_dump($headers);Code language: PHP (php)
array(2) < [0]=> string(10) "first_name" [1]=> string(9) "last_name" >Code language: PHP (php)

4) A practical example of the PHP explode() function

The following str_after() function returns the remainder of a string after the first occurrence of a string:

 function str_after($str, $search) < return $search === '' ? $str : array_reverse(explode($search, $str, 2))[0]; >Code language: PHP (php)
  • First, split the string into an array of two elements separated by the $search string.
  • Second, reverse the result array and return the first element of the result array.

The following example uses the str_after() function to get the domain name part of an email:

 // . echo str_after('john.doe@phptutorial.net', '@');Code language: PHP (php)
phptutorial.netCode language: PHP (php)

Summary

  • Use the PHP explode() function to return an array of strings by splitting a string by a separator.

Источник

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() — Объединяет элементы массива в строку

Источник

explode

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

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

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

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

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

Замечание:

До PHP 8.0 функция implode() принимала параметры в любом порядке. Функция explode() никогда этого не поддерживала: убедитесь в том, что separator указан перед аргументом string .

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

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

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

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

Версия Описание
8.0.0 explode() теперь выбрасывает TypeError , если параметр separator является пустой строкой ( «» ). Ранее вместо исключения explode() возвращала false .

Примеры

Пример #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» ;
$input3 = ‘,’ ;
var_dump ( explode ( ‘,’ , $input1 ) );
var_dump ( explode ( ‘,’ , $input2 ) );
var_dump ( explode ( ‘,’ , $input3 ) );

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

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

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

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

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

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

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

Примечания

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

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

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

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

Источник

PHP explode() Function

The explode() function breaks a string into an array.

Note: The «separator» parameter cannot be an empty string.

Note: This function is binary-safe.

Syntax

Parameter Values

Parameter Description
separator Required. Specifies where to break the string
string Required. The string to split
limit Optional. Specifies the number of array elements to return.
  • Greater than 0 — Returns an array with a maximum of limit element(s)
  • Less than 0 — Returns an array except for the last -limit elements()
  • 0 — Returns an array with one element

Technical Details

Return Value: Returns an array of strings
PHP Version: 4+
Changelog: The limit parameter was added in PHP 4.0.1, and support for negative limits were added in PHP 5.1.0

More Examples

Example

Using the limit parameter to return a number of array elements:

// negative limit
print_r(explode(‘,’,$str,-1));
?>

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Javascript array length returns 0
Оцените статью