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
4.0.1 O parâmetro limit 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('|'$str2));

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

O exemplo acima irá imprimir:

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 add a note

User Contributed Notes 5 notes

up
6
Emilio Bravo
3 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
2
henrik Schmidt
3 years ago
"Return value" text needs updating for php 8, an empty delimiter now throws an Exception.
up
3
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
-5
David Spector
3 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
up
-26
leandro at primersistemas dot com dot br
3 years ago
function aexplode($delimiters,$string,$trimduplicate = false) {
    if (!is_array($delimiters))
        return explode($delimiters,$string);
    $stringaux = str_replace($delimiters, $delimiters[0], $string);
    if ($trimduplicate)
        while (strpos($stringaux,$delimiters[0].$delimiters[0]) !== false)
            $stringaux = str_replace($delimiters[0].$delimiters[0],$delimiters[0],$stringaux);
    return explode($delimiters[0],$stringaux);
}

This functions will work and accept array.
To Top