Funkcja preg_split() PHP
Przykład
Użyj preg_split(), aby podzielić datę na jej składniki:
<?php
$date = "1970-01-01 00:00:00";
$pattern = "/[-\s:]/";
$components =
preg_split($pattern, $date);
print_r($components);
?>
Definicja i użycie
Funkcja preg_split()
dzieli ciąg na tablicę, używając dopasowań wyrażenia regularnego jako separatorów.
Składnia
preg_split(pattern, string, limit, flags)
Wartości parametrów
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:
|
Szczegóły techniczne
Wartość zwrotu: | Zwraca tablicę podciągów, gdzie każdy element odpowiada części ciągu wejściowego oddzielonego dopasowaniem wyrażenia regularnego |
---|---|
Wersja PHP: | 4+ |
Więcej przykładów
Przykład
Używając flagi 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);
?>
Przykład
Korzystanie z flagi PREG_SPLIT_OFFSET_CAPTURE:
<?php
$date = "1970-01-01";
$pattern = "/-/";
$components =
preg_split($pattern, $date, -1,
PREG_SPLIT_OFFSET_CAPTURE);
print_r($components);
?>
❮ Dokumentacja RegExp PHP