PHP 8.5.0 Alpha 1 available for testing

explode

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

explodeDivide una string en segmentos

Descripción

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

explode() retorna un array de strings, cada una de ellas siendo una substring del parámetro string extraída utilizando el separador separator.

Parámetros

separator

El separador.

string

La string inicial.

limit

Si limit está definido y es positivo, el array retornado contiene, como máximo, limit elementos, y el último elemento contendrá el resto de la string.

Si el parámetro limit es negativo, todos los elementos, excepto los últimos -limit elementos, son retornados.

Si limit vale cero, es tratado como si valiera 1.

Nota:

Antes de PHP 8.0, implode() aceptaba sus parámetros en cualquier orden. explode() nunca ha soportado esto: se debe asegurar que el parámetro separator esté colocado antes del parámetro string.

Valores devueltos

Retorna un tableau de strings creadas al dividir la string del parámetro string en varios trozos siguiendo el parámetro separator.

Si separator es una string vacía (""), explode() lanzará una ValueError. Si separator contiene un valor que no está contenido en string así como un valor negativo para el parámetro limit, entonces explode() retornará un tableau vacío, de lo contrario, un tableau conteniendo la string string entera. Si los valores de separator aparecen al inicio o al final de string, estos valores serán añadidos como un valor de un array vacío ya sea en la primera o última posición del array retornado respectivamente.

Historial de cambios

Versión Descripción
8.0.0 explode() lanzará ahora una ValueError cuando el parámetro separator es una string vacía (""). Anteriormente, explode() retornaba false.

Ejemplos

Ejemplo #1 Ejemplo con explode()

<?php
// Ejemplo 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo
$pieces[0], PHP_EOL; // piece1
echo $pieces[1], PHP_EOL; // piece2

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

?>

Ejemplo #2 Ejemplo de valores retornados por la función explode()

<?php
/* Una string que no contiene delimitador retornará un array
conteniendo solo un elemento representando la string original */
$input1 = "hello";
$input2 = "hello,there";
$input3 = ',';
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );
var_dump( explode( ',', $input3 ) );

?>

El resultado del ejemplo sería:

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

Ejemplo #3 Ejemplo con explode() y el parámetro limit

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

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

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

El resultado del ejemplo sería:

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

Notas

Nota: Esta función es segura binariamente.

Ver también

  • preg_split() - Divide una cadena mediante expresión regular
  • str_split() - Convierte un string en un array
  • mb_split() - Divide una string en un array utilizando una expresión regular multibyte
  • str_word_count() - Cuenta el número de palabras utilizadas en un string
  • strtok() - Divide una cadena en segmentos
  • implode() - Une elementos de un array en un string

add a note

User Contributed Notes 4 notes

up
39
Gerben
3 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
16
marc
1 year 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
12
bocoroth
4 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
3
Alejandro-Ihuit
2 years 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