PHP preg_split() Function
PHP Regular Expressions (PCRE)
The preg_split function splits a string by a regular expression.
Syntax
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
Splits a given string by a regular expression.
Parameter Description:
-
$pattern: the pattern used for searching, as a string.
-
$subject: the input string.
-
$limit: optional; if specified, limits the number of substrings produced to at most limit, with the last returned substring containing all remaining parts. A limit value of -1, 0 or null means "no limit"; as per PHP's convention, you can use null to skip setting flags.
-
$flags: optional, can be any combination of the flags below (combined with the bitwise OR | operator):
- PREG_SPLIT_NO_EMPTY: If this flag is set, preg_split() will return only the non-empty parts after splitting.
- PREG_SPLIT_DELIM_CAPTURE: If this flag is set, the parenthesized subpatterns in the delimiter pattern will be captured and returned.
- PREG_SPLIT_OFFSET_CAPTURE: If this flag is set, for every occurring match the appended string offset will be returned as well. Note: this will change every element in the returned array, so that each element becomes an array consisting of the substring at index 0 and its offset within subject at index 1.
Return Value
Returns an array of substrings of subject split by the pattern boundary.
Example
Get a part of the search string
The execution result is as follows:
Array
(
[0] => hypertext
[1] => language
[2] => programming
)
Split a string into the characters that compose it
The execution result is as follows:
Array
(
[0] => r
[1] => u
[2] => n
[3] => o
[4] => o
[5] => b
)
Split a string and get the offset of each part
The execution result is as follows:
Array
(
[0] => Array
(
[0] => hypertext
[1] => 0
)
[1] => Array
(
[0] => language
[1] => 10
)
[2] => Array
(
[0] => programming
[1] => 19
)
)