(PHP 4, PHP 5, PHP 7, PHP
explode — Split a string by a string
Description
explode(string $separator
, string $string
, int $limit
= PHP_INT_MAX
): array
Parameters
-
separator
-
The boundary string.
-
string
-
The input string.
-
limit
-
If
limit
is set and positive, the returned array will contain
a maximum oflimit
elements with the last
element containing the rest ofstring
.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 strings
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
<?php
// 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
<?php
/*
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
<?php
$str = 'one|two|three|four';// 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
Gerben ¶
1 year ago
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:
<?php
$uri
= '';
$parts = explode('/', $uri);
var_dump($parts);
?>
Will output:
array(1) {
[0]=>
string(0) ""
}
And not:
array(0) {
}
bocoroth ¶
2 years ago
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" }
Alejandro-Ihuit ¶
6 months ago
If you want to directly take a specific value without having to store it in another variable, you can implement the following:
$status = 'Missing-1';
echo $status_only = explode('-', $status)[0];
// Missing
За последние 24 часа нас посетили 14519 программистов и 1012 роботов. Сейчас ищут 448 программистов …
explode
(PHP 4, PHP 5, PHP 7)
explode — Разбивает строку с помощью разделителя
Описание
array explode
( string $delimiter
, string $string
[, int $limit
] )
Список параметров
-
delimiter
-
Разделитель.
-
string
-
Входная строка.
-
limit
-
Если аргумент
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()
<?php
// Пример 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()
<?php
/*
Строка, которая не содержит разделителя, будет
просто возвращать массив с одним значением оригинальной строки.
*/
$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
<?php
$str = 'один|два|три|четыре';// положительный лимит
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() — Объединяет элементы массива в строку
Вернуться к: Обработка строк
I’m new in PHP programming. I need your help to finish my homework.
I want to explode the following sentence: I love my band and my cat into arrays.
But I need to use space and word and as delimiters. So it should become like this:
$arr[0] -> I
$arr[1] -> love
$arr[2] -> my
$arr[3] -> band
$arr[4] -> my
$arr[5] -> cat
I have tried like this:
$words = "I love my band and my cat"
$stopwords = "/ |and/";
$arr = explode($stopwords, $words);
But the problem is, it also removes characters and from word band so it becomes like this:
$arr[0] -> I
$arr[1] -> love
$arr[2] -> my
$arr[3] -> b
$arr[4] -> my
$arr[5] -> cat
This is not what I want. I want to remove the word that exactly and, not word that contains and characters.
Is there anyway to solve this? Can anybody help me? Thank you very much..
Matt Busche
14.1k5 gold badges36 silver badges61 bronze badges
asked Feb 20, 2013 at 3:13
4
If you want to avoid splitting out and
in the middle of a word, you have to filter the result list (array_diff
), or use a more complex regex. Then also consider preg_match_all
instead of splitting:
preg_match_all('/ (?! b and b) (b w+ b) /x', $input, $words);
This will only search for consecutive word-characters, instead of breaking up on spaces. And the assertion ?!
will skip occurences of and
.
answered Feb 20, 2013 at 3:23
mariomario
143k20 gold badges236 silver badges289 bronze badges
1
Try this:
<?php
$words = "I love my band and my cat";
$clean = str_replace(" and",'',$words);
$array = explode(" ",$clean);
print_r($array);
?>
answered Feb 20, 2013 at 3:19
ionFishionFish
1,0041 gold badge8 silver badges19 bronze badges
4
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 ) : array
Code language: PHP (php)
The explode()
function has the following parameters:
$separator
is the delimiter that theexplode()
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 (,
):
<?php
$str = 'first_name,last_name,email,phone';
$headers = explode(',', $str);
print_r($headers);
Code language: PHP (php)
Output:
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)
Output:
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)
Output:
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)
Output:
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:
<?php
function str_after($str, $search)
{
return $search === '' ? $str : array_reverse(explode($search, $str, 2))[0];
}
Code language: PHP (php)
How it works.
- 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:
<?php
// ...
echo str_after('john.doe@phptutorial.net', '@');
Code language: PHP (php)
Output:
phptutorial.net
Code language: PHP (php)
Summary
- Use the PHP
explode()
function to return an array of strings by splitting a string by a separator.
Did you find this tutorial useful?
The PHP explode()
function converts a string to an array. Each of the characters in the string is given an index that starts from 0. Like the built-in imlode()
function, the explode function does not modify the data (string).
Syntax of the explode()
Function
The explode()
function takes in three parameters:
- the separator
- the string to convert to an array
- and the limit
The full syntax looks like this:
explode(separator, string, limit)
Unlike implode()
which works even if the separator is not provided, the explode()
function won’t work without the separator. So, just like the string split into an array, the separator is required. You can use the limit parameter to specify the number of arrays expected. It is optional.
Examples of implode()
Let’s say that I have the string «Hello World». If the string is passed into an explode()
function, Hello
takes an index of 0 in the array, and World
takes an index of 1. Remember that arrays use zero-based indexing.
$str = "Hello world";
$newStr = explode(" ", $str);
// We are printing an array, so we can use print_r()
print_r($newStr);
If you specify a limit in the explode()
function, the index(es) won’t be more than that number. For example, if you specify 2, all the strings would show, but the index won’t be more than 2.
$str = "CSS, HTML, PHP, Java, JavaScript";
$newStr = explode(" ", $str, 2);
// We are printing an array, so we can use print_r()
print_r($newStr);
You can see that the first element takes an index of 0 and the rest of the comma-separated elements take 1. The index is not more than the limit of 2 specified.
The explode()
function looks at spaces in the string to split the string into an array. If you type two different words together, they are treated as one:
$str = "CSS HTMLPHP Java JavaScript";
$newStr = explode( " ", $str);
// We are printing an array, so we can use print_r()
print_r($newStr);
You can see that HTML and PHP got ptinted together because there was no space between them.
Conclusion
This article showed you how to use the explode()
function in PHP.
Note that unlike implode()
which works without the separator, the separator is very important in explode()
. If you don’t specify a separator, explode()
won’t work as expected.
$str = "CSS, HTML, PHP, Java, JavaScript";
$newStr = explode($str, 2);
// We are printing an array, so we can use print_r()
print_r($newStr);
And if you leave the separator as an empty string, you get an error:
Thank you for reading.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started