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" }
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 !==
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With