explode

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

explodeScinde une chaîne de caractères en segments

Description

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

explode() retourne un tableau de chaînes de caractères, chacune d'elle étant une sous-chaîne du paramètre string extraite en utilisant le séparateur separator.

Liste de paramètres

separator

Le séparateur.

string

La chaîne initiale.

limit

Si limit est défini et positif, le tableau retourné contient, au maximum, limit éléments, et le dernier élément contiendra le reste de la chaîne.

Si le paramètre limit est négatif, tous les éléments, excepté les -limit derniers éléments sont retournés.

Si limit vaut zéro, il est traité comme valant 1.

Note:

Antérieur à PHP 8.0, implode() acceptait ses paramètres dans n'importe quel ordre. explode() n'a jamais supporté ceci : vous devez vous assurer que le paramètre separator soit placé avant le paramètre string.

Valeurs de retour

Retourne un tableau de chaînes de caractères créées en scindant la chaîne du paramètre string en plusieurs morceaux suivant le paramètre separator.

Si separator est une chaîne vide (""), explode() retournera false. Si separator contient une valeur qui n'est pas contenue dans string ainsi qu'une valeur négative pour le paramètre limit, alors explode() retournera un tableau vide, sinon, un tableau contenant la chaîne string entière. Si les valeurs de separator apparaissent au début ou à la fin de string, ces valeurs seront ajouté comme une valeur d'un array vide soit en la première ou dernière position du array retourné respectivement.

Historique

Version Description
8.0.0 explode() lancera désormais une ValueError quand le paramètre separator est donné une chaîne vide ("").

Exemples

Exemple #1 Exemple avec explode()

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

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

?>

Exemple #2 Exemple de valeurs retournées par la fonction explode()

<?php
/* Une chaîne qui ne contient pas de délimiteur va retourner un tableau
   contenant qu'un seul élément représentant la chaîne originale */
$input1 "hello";
$input2 "hello,there";
$input3 ',';
var_dumpexplode','$input1 ) );
var_dumpexplode','$input2 ) );
var_dumpexplode','$input3 ) );

?>

L'exemple ci-dessus va afficher :

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

Exemple #3 Exemple avec explode() et le paramètre limit

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

// limit positif
print_r(explode('|'$str2));

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

L'exemple ci-dessus va afficher :

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

Notes

Note: Cette fonction gère les chaînes binaires.

Voir aussi

  • preg_split() - Éclate une chaîne par expression rationnelle
  • str_split() - Convertit une chaîne de caractères en tableau
  • mb_split() - Scinde une chaîne en tableau avec une expression rationnelle multi-octets
  • str_word_count() - Compte le nombre de mots utilisés dans une chaîne
  • strtok() - Coupe une chaîne en segments
  • implode() - Rassemble les éléments d'un tableau en une chaîne

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