Explode string into array with no empty elements? Explode string into array with no empty elements? arrays arrays

Explode string into array with no empty elements?


Try preg_split.

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


array_filter will remove the blank fields, here is an example without the filter:

print_r(explode('/', '1/2//3/'))

prints:

Array(    [0] => 1    [1] => 2    [2] =>    [3] => 3    [4] =>)

With the filter:

php> print_r(array_filter(explode('/', '1/2//3/')))

Prints:

Array(    [0] => 1    [1] => 2    [3] => 3)

You'll get all values that resolve to "false" filtered out.

see http://uk.php.net/manual/en/function.array-filter.php


Just for variety:

array_diff(explode('/', '1/2//3/'), array(''))

This also works, but does mess up the array indexes unlike preg_split. Some people might like it better than having to declare a callback function to use array_filter.