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);

Output:

Array
(
    [0] =>  PHP
    [1] =>  CSS 
    [2] =>  HTML 
    [3] =>  AJAX 
    [4] =>  JSON
)

To split a string into a array simply pass the string and a regexp for preg_split(); to match and search, adding a third parameter (limit) allows you to set the number of “matches” to perform, the remaining string will be added to the end of the array.

The fourth parameter is (flags) here we use the PREG_SPLIT_NO_EMPTY which prevents our array from containing any empty keys / values.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents