Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode string into array with no empty elements?

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" } 
like image 237
Glenn Moss Avatar asked Sep 15 '08 16:09

Glenn Moss


People also ask

How do you remove empty elements from an array?

We can use an array instance's filter method to remove empty elements from an array. To remove all the null or undefined elements from an array, we can write: const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ]; const filtered = array. filter((el) => { return el !==

Can string split return empty array?

If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.

Can you have an empty element in an array?

The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it. Let's run through some examples.

What happens if you split an empty string?

The natural consequence is that if the string does not contain the delimiter, a singleton array containing just the input string is returned, Second, remove all the rightmost empty strings. This is the reason ",,,". split(",") returns empty array.


2 Answers

Try preg_split.

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

like image 53
ceejayoz Avatar answered Oct 11 '22 09:10

ceejayoz


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

like image 41
Dave Gregory Avatar answered Oct 11 '22 09:10

Dave Gregory