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 match a space using 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 get the first match when using regex in PHP?
- How to match the end of a string when using regex in PHP?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match special characters?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match UUID?
- How to match strings starting with a certain string using PHP regex?
See more codes...