php-regexHow to split string by regex in PHP?
Splitting a string by regex in PHP can be done using the preg_split() function.
$string = 'This is a string';
$regex = '/\s+/';
$words = preg_split($regex, $string);
print_r($words);
The output of the above code will be:
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
)
The preg_split() function takes two parameters:
$regex- The regular expression to use for splitting the string.$string- The string to split.
The function will return an array of strings split by the regular expression.
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a zip code?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match a year?
- How to use PHP regex with zero or more occurrences?
- How to match a single quote in PHP regex?
- How to use PHP regex to match an exact string?
- How to use PHP regex with the "x" modifier?
- How to match a double quote in PHP regex?
- How to use PHP regex to match an XML tag?
See more codes...