explode

(PHP 4, PHP 5, PHP 7, PHP 8)

explodeDivide uma string com base em outra string

Descrição

explode(string $separator, string $string, int $limit = PHP_INT_MAX): array

Retorna um array de strings, sendo que cada uma é uma sub-string da string, formado pela separação dela nos limites formados pela string informada em separator.

Parâmetros

separator

A string que define o separador.

string

A string de entrada.

limit

Se limit estiver definido e for positivo, o array retornado conterá um máximo de limit elementos com o último elemento contendo todo o restante da string.

Se limit for negativo, todos os componentes exceto os (último - limit) são retornados.

Se limit for zero, é tratado como 1.

Nota:

Antes do PHP 8.0, implode() aceitava seus dois primeiros parâmetros em qualquer ordem. A função explode() nunca suportou isto: deve-se garantir que o parâmetro separator vem antes do parâmetro string.

Valor Retornado

Retorna um array de strings criado pela separação da string nos limites formados pelo parâmetro separator.

Se separator for uma string vazia (""), explode() lança um ValueError. Se separator contiver um valor não contido em string e um valor negativo for usado em limit, um array vazio será retornado, caso contrário um array contendo string será retornado. Se valores de separator aparecerem no início ou no final da string, said values elementos de array vazios serão adicionados na posição inicial ou final do array retornado, respectivamente.

Registro de Alterações

Versão Descrição
8.0.0 explode() agora lança um ValueError quando separator é informado com uma string vazia (""). Anteriormente, explode() retornava false nesse caso.

Exemplos

Exemplo #1 Exemplos de explode()

<?php
// Exemplo 1
$pizza = "fatia1 fatia2 fatia3 fatia4 fatia5 fatia6";
$fatias = explode(" ", $pizza);
echo
$fatias[0]; // fatia1
echo $fatias[1]; // fatia2

// Exemplo 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list(
$user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo
$user; // foo
echo $pass; // *

?>

Exemplo #2 Exemplo de retorno de explode()

<?php
/*
Uma string que não contém o separador simplesmente
irá retornar um array de 1 elemento com a string original.
*/
$input1 = "olá";
$input2 = "olá,mundo";
$input3 = ',';
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );
var_dump( explode( ',', $input3 ) );

?>

O exemplo acima produzirá:

array(1)
(
    [0] => string(3) "olá"
)
array(2)
(
    [0] => string(3) "olá"
    [1] => string(5) "mundo"
)
array(2)
(
    [0] => string(0) ""
    [1] => string(0) ""
)

Exemplo #3 Exemplos do parâmetro limit

<?php
$str
= 'um|dois|três|quatro';

// limite positivo
print_r(explode('|', $str, 2));

// limite negativo
print_r(explode('|', $str, -1));
?>

O exemplo acima produzirá:

Array
(
    [0] => um
    [1] => dois|três|quatro
)
Array
(
    [0] => um
    [1] => dois
    [2] => três
)

Notas

Nota: Esta função é compatível com dados binários.

Veja Também

add a note

User Contributed Notes 4 notes

up
29
Gerben
2 years 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) {
}
up
9
marc
8 months ago
If your data is smaller than the expected count with the list expansion:

<?php
$data
= "foo:*:1023:1000::/home/foo:/bin/sh";
list(
$user, $pass, $uid, $gid, $gecos, $home, $shell,$nu) = explode(":", $data);
?>

The result is a warning not an error:

PHP Warning: Undefined array key 7 in ...

The solution is to pad the array to the expected length:

<?php
$data
= "foo:*:1023:1000::/home/foo:/bin/sh";
list(
$user, $pass, $uid, $gid, $gecos, $home, $shell,$nu) = array_pad( explode(":", $data), 8, "");
// where 8 is the count of the list arguments
?>
up
11
bocoroth
3 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" }
up
0
Alejandro-Ihuit
1 year 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
To Top