explode

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

explodeDivide uma string em strings

Valor Retornado

explode(string $delimiter, string $string, int $limit = ?): array

Retorna uma matriz de strings, cada uma como substring de string formada pela divisão dela a partir do delimiter.

Parâmetros

delimiter

O delimitador.

string

A string de entrada.

limit

Se limit é definido, o array retornado irá conter o máximo de elementos igual a limit com o último elemento contendo o resto da string.

Se o parâmetro limit é negativo, todos componentes exceto o último -limit são retornados.

Ainda que implode() pode por razões históricas aceitar seus parâmetros em uma das duas ordens, explode() não pode. Você deve assegurar que o argumento delimiter vem antes do argumento string.

Valor Retornado

Se delimiter é uma string vazia (""), explode() irá retornar false. Se delimiter contém um valor que não contém em string, então explode() irá retornar um array contendo string.

Changelog

Versão Descrição
5.1.0 Suporte a limit negativo foi adicionado

Exemplos

Exemplo #1 explode() exemplos

<?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; // *

?>

Exemplo #2 Exemplos de parâmetro limit

<?php
$str
= 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));

// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));
?>

O exemplo acima produzirá:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

Notas

Nota: Esta função é binary-safe.

Veja Também

add a note

User Contributed Notes 7 notes

up
19
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) {
}
up
12
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" }
up
2
henrik Schmidt
2 years ago
"Return value" text needs updating for php 8, an empty delimiter now throws an Exception.
up
0
Alejandro-Ihuit
5 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
up
-10
Emilio Bravo
2 years ago
$string = "PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION";
$exploded = explode("::",$string);
/*

explode('::',$string) = eliminate every :: and for each division of ::make an array element

Example:

PDO::ERRMODE_EXCEPTION (exploded) = array     (
                                                    [0] => string PDO
                                                    [1] => string ERRMODE_EXCEPTION
                                               )
Example:

$exploded[0] = "PDO";
*/
foreach ($exploded as $index) {
    echo $index . "\n";
}
/*

Output:

PDO
ATTR_ERRMODE => PDO
ERRMODE_EXCEPTION

*/
up
-16
joshuachidiebere17217 at gmail dot com
1 year ago
<?php
/*Array to split*/
$task =["Teach","Assess","Record ","Examine","Investigate"];
/*use Implode() function to convert
$task into arrays of string
*/
$string=implode(",", $task);
/*use explode() function to seperate $string into different
$task into arrays of string
*/ 
explode(",", $string);
foreach (
$task as $variable => $tk) {
$variable>0;
$variable++;
echo
'$variable_'.$variable.' is ' .$tk.'<br>';
}
echo
min(3,6);
?>
up
-40
David Spector
2 years ago
When using 'explode' to create an array of strings from a user-specified string that contains newline characters, you may wish the resulting array to correctly reflect the user's intentions by ignoring any final empty line (many users like to end multi-line input with a final newline, for clarity).

Here is a function to call after 'explode' to support this effect:

// When using explode, delete the last line in the array of lines when it is empty
function IgnoreEmptyLastLine(&$linesArr)
    {
    $last=count($linesArr)-1;
    if ($last>=0 && !$linesArr[$last])
        unset($linesArr[$last]);
    } // IgnoreEmptyLastLine
To Top