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 to search for, as a string.
$subject: The input string.
$limit: Optional. If specified, limits the number of substrings returned to at most limit, and the last substring will contain all the remaining parts. A limit value of -1, 0, or null means "no limit". As a PHP standard, you can use null to skip setting flags.
$flags: Optional. Can be any combination of the following flags (combined with bitwise OR |):
- PREG_SPLIT_NO_EMPTY: If this flag is set, preg_split() will only return the non-empty parts after splitting.
- PREG_SPLIT_DELIM_CAPTURE: If this flag is set, parenthesized expressions in the delimiter pattern will be captured and returned.
- PREG_SPLIT_OFFSET_CAPTURE: If this flag is set, for each occurring match, the string offset will be appended in the return. Note: This will change each element of the returned array, making each element an array consisting of the 0th element as the split substring and the 1st element as the offset of the substring in subject.
Return Value
Returns an array of substrings obtained by splitting subject along boundaries matching pattern.
Examples
Get parts of the search string
The output is as follows:
Array
(
[0] => hypertext
[1] => language
[2] => programming
)
Split a string into its constituent characters
The output 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 output is as follows:
Array
(
[0] => Array
(
[0] => hypertext
[1] => 0
)
[1] => Array
(
[0] => language
[1] => 10
)
[2] => Array
(
[0] => programming
[1] => 19
)
)
Other Extensions