Função PHP preg_split()
Exemplo
Use preg_split() para dividir uma data em seus componentes:
<?php
$date = "1970-01-01 00:00:00";
$pattern = "/[-\s:]/";
$components =
preg_split($pattern, $date);
print_r($components);
?>
Definição e uso
A preg_split()
função quebra uma string em uma matriz usando correspondências de uma expressão regular como separadores.
Sintaxe
preg_split(pattern, string, limit, flags)
Valores de parâmetro
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:
|
Detalhes técnicos
Valor de retorno: | Retorna uma matriz de substrings onde cada item corresponde a uma parte da string de entrada separada por uma correspondência da expressão regular |
---|---|
Versão do PHP: | 4+ |
Mais exemplos
Exemplo
Usando o sinalizador 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);
?>
Exemplo
Usando o sinalizador PREG_SPLIT_OFFSET_CAPTURE:
<?php
$date = "1970-01-01";
$pattern = "/-/";
$components =
preg_split($pattern, $date, -1,
PREG_SPLIT_OFFSET_CAPTURE);
print_r($components);
?>
❮ Referência PHP RegExp