Explode string into array with no empty elements?

arrays, explode, filtering, php, string

Solution

Try preg_split.

`$exploded = preg_split('@/@', '1/2//3/', -1, PREG_SPLIT_NO_EMPTY);`

Problem

PHP's explode function returns an array of strings split on some provided substring. It will return empty strings when there are leading, trailing, or consecutive delimiters, like this: ``` var_dump(explode('/', '1/2//3/')); array(5) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(0) "" [3]=> string(1) "3" [4]=> string(0) "" } ``` Is there some different function or option or anything that would return everything except the empty strings? ``` var_dump(different_explode('/', '1/2//3/')); array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" } ```

Original source