Split string into array by a regular expression
suggest change$string = "0| PHP 1| CSS 2| HTML 3| AJAX 4| JSON";
//[0-9]: Any single character in the range 0 to 9
// + : One or more of 0 to 9
$array = preg_split("/[0-9]+\|/", $string, -1, PREG_SPLIT_NO_EMPTY);
//Or
// [] : Character class
// \d : Any digit
// + : One or more of Any digit
$array = preg_split("/[\d]+\|/", $string, -1, PREG_SPLIT_NO_EMPTY);
Array
(
[0] => PHP
[1] => CSS
[2] => HTML
[3] => AJAX
[4] => JSON
)
Each piece keeps the spaces around the label. The last piece has no trailing space.
To split a string into an array, pass the string and a regular expression to preg_split(). The third parameter (limit) sets how many splits to perform; the remainder of the string is the last element.
The fourth parameter (flags) is PREG_SPLIT_NO_EMPTY here, which keeps empty pieces out of the array.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents