Fonction PHP preg_split()
Exemple
Utilisez preg_split() pour diviser une date en ses composants :
<?php
$date = "1970-01-01 00:00:00";
$pattern = "/[-\s:]/";
$components =
preg_split($pattern, $date);
print_r($components);
?>
Définition et utilisation
La preg_split()
fonction sépare une chaîne dans un tableau en utilisant les correspondances d'une expression régulière comme séparateurs.
Syntaxe
preg_split(pattern, string, limit, flags)
Valeurs des paramètres
Parameter | Description |
---|---|
pattern | Required. A regular expression determining what to use as a separator |
string | Required. The string that is being split |
limit | Optional. Defaults to -1, meaning unlimited. Limits the number of elements that the returned array can have. If the limit is reached before all of the separators have been found, the rest of the string will be put into the last element of the array |
flags | Optional. These flags provide options to change the returned array:
|
Détails techniques
Valeur de retour : | Renvoie un tableau de sous-chaînes où chaque élément correspond à une partie de la chaîne d'entrée séparée par une correspondance de l'expression régulière |
---|---|
Version PHP : | 4+ |
Plus d'exemples
Exemple
Utilisation de l'indicateur PREG_SPLIT_DELIM_CAPTURE :
<?php
$date = "1970-01-01 00:00:00";
$pattern = "/([-\s:])/";
$components =
preg_split($pattern, $date, -1,
PREG_SPLIT_DELIM_CAPTURE);
print_r($components);
?>
Exemple
Utilisation de l'indicateur PREG_SPLIT_OFFSET_CAPTURE :
<?php
$date = "1970-01-01";
$pattern = "/-/";
$components =
preg_split($pattern, $date, -1,
PREG_SPLIT_OFFSET_CAPTURE);
print_r($components);
?>
❮ Référence PHP RegExp