phpday 2027 - Call for Papers

explode

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

explode — Divide una stringa tramite una stringa

Descrizione

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

Restituisce un array di stringhe, ciascuna delle quali è una sottostringa di string ottenuta dividendola in corrispondenza dei confini formati dalla stringa separator.

Elenco dei parametri

separator

La stringa di confine.

string

La stringa di input.

limit

Se limit è impostato e positivo, l'array restituito conterrà al massimo limit elementi, e l'ultimo elemento conterrà il resto di string.

Se il parametro limit è negativo, vengono restituiti tutti i componenti tranne gli ultimi -limit.

Se il parametro limit è zero, viene trattato come 1.

Nota:

Prima di PHP 8.0, implode() accettava i suoi parametri in entrambi gli ordini. explode() non lo ha mai supportato: occorre assicurarsi che l'argomento separator preceda l'argomento string.

Valori restituiti

Restituisce un array di string creato dividendo il parametro string in corrispondenza dei confini formati da separator.

Se separator è una string vuota (""), explode() lancia un ValueError. Se separator contiene un valore che non è contenuto in string e viene usato un limit negativo, verrà restituito un array vuoto, altrimenti verrà restituito un array contenente string. Se i valori di separator compaiono all'inizio o alla fine di string, tali valori verranno aggiunti come valore vuoto dell'array rispettivamente nella prima o nell'ultima posizione dell'array restituito.

Log delle modifiche

Versione Descrizione
8.0.0 explode() ora lancia un ValueError quando al parametro separator viene passata una stringa vuota (""). In precedenza, explode() restituiva invece false.

Esempi

Example #1 Esempi di explode()

<?php
// Esempio 1
$pizza  = "pezzo1 pezzo2 pezzo3 pezzo4 pezzo5 pezzo6";
$pieces = explode(" ", $pizza);
echo $pieces[0], PHP_EOL; // pezzo1
echo $pieces[1], PHP_EOL; // pezzo2

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

Example #2 Esempi dei valori restituiti da explode()

<?php
/* 
   Una stringa che non contiene il delimitatore restituirà
   semplicemente un array di lunghezza uno con la stringa originale.
*/
$input1 = "ciao";
$input2 = "ciao,mondo";
$input3 = ',';
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );
var_dump( explode( ',', $input3 ) );

?>

Il precedente esempio visualizzerà:

array(1) {
  [0]=>
  string(4) "ciao"
}
array(2) {
  [0]=>
  string(4) "ciao"
  [1]=>
  string(5) "mondo"
}
array(2) {
  [0]=>
  string(0) ""
  [1]=>
  string(0) ""
}

Example #3 Esempi del parametro limit

<?php
$str = 'uno|due|tre|quattro';

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

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

Il precedente esempio visualizzerà:

Array
(
    [0] => uno
    [1] => due|tre|quattro
)
Array
(
    [0] => uno
    [1] => due
    [2] => tre
)

Note

Nota:

Questa funzione è binary-safe.

Vedere anche:

  • preg_split() - Suddivide una stringa tramite un'espressione regolare
  • str_split() - Converte una stringa in un array
  • mb_split() - Split multibyte string using regular expression
  • str_word_count() - Restituisce informazioni sulle parole usate in una stringa
  • strtok() - Divide una stringa in token
  • implode() - Unisce gli elementi di un array con una stringa

+add a note

User Contributed Notes 3 notes

up
46
Gerben
4 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
21
marc
3 years 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
16
bocoroth
5 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" }
To Top