PHPpreg_split() Function
Example
Use preg_split() to split a date into its components:
<?php
$date = "1970-01-01 00:00:00";
$pattern = "/[-\s:]/";
$components = preg_split($pattern, $date);
print_r($components);
?>
Try it Yourself »$date = "1970-01-01 00:00:00";
$pattern = "/[-\s:]/";
$components = preg_split($pattern, $date);
print_r($components);
?>
Definition and Usage
Thepreg_split() function breaks a string into an array using matches of a regular expression as separators.
Syntax
preg_split(pattern, string, limit, flags)
Parameter Values
| 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 ofelements that the returned array can have. If the limit is reachedbefore all of the separators have been found, the rest of the stringwill be put into the last element of the array |
| flags | Optional. These flags provide options to change the returned array:
|
Technical Details
| Return Value: | Returns an array of substrings where each item corresponds to apart of the input string separated by a match of the regularexpression |
|---|---|
| PHP Version: | 4+ |
More Examples
Example
Using the PREG_SPLIT_DELIM_CAPTURE flag:
<?php
$date = "1970-01-01 00:00:00";
$pattern = "/([-\s:])/";
$components = preg_split($pattern, $date, -1,
PREG_SPLIT_DELIM_CAPTURE);
print_r($components);
?>
Try it Yourself »$date = "1970-01-01 00:00:00";
$pattern = "/([-\s:])/";
$components = preg_split($pattern, $date, -1,
PREG_SPLIT_DELIM_CAPTURE);
print_r($components);
?>
Example
Using the PREG_SPLIT_OFFSET_CAPTURE flag:
<?php
$date = "1970-01-01";
$pattern = "/-/";
$components = preg_split($pattern, $date, -1,
PREG_SPLIT_OFFSET_CAPTURE);
print_r($components);
?>
Try it Yourself »$date = "1970-01-01";
$pattern = "/-/";
$components = preg_split($pattern, $date, -1,
PREG_SPLIT_OFFSET_CAPTURE);
print_r($components);
?>
❮ PHP RegExp Reference

