My PHP code below will explode a string into array. It allows to use multiple delimiters for detecting where the array values should be from the string.
In the demo one of the delimiter values is a space. The problem is if the string has more than 1 consecutive space, it will generate empty array values.
For example key key2 key3 key4 would generate array with:
Array
(
[0] => key
[1] => key2
[2] => key3
[3] =>
[4] => key4
)
and the desired output is:
Array
(
[0] => key
[1] => key2
[2] => key3
[4] => key4
)
How can I fix this?
/**
* Explode a string into array with multiple delimiters instead of the default 1 delimeter that explode() allows!
* @param array $delimiters - array(',', ' ', '|') would make a string with spaces, |, or commas turn into array
* @param string $string text with the delimeter values in it that will be truned into an array
* @return array - array of items created from the string where each delimiter in string made a new array key
*/
function multiexplode ($delimiters, $string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$array = explode($delimiters[0], $ready);
$array = array_map('trim', $array);
return $array;
}
$tagsString = 'PHP JavaScript,WebDev Apollo jhjhjh';
$tagsArray = multiexplode(array(',',' '), $tagsString);
print_r($tagsArray);
Output array
Array
(
[0] => PHP
[1] => JavaScript
[2] => WebDev
[3] => Apollo
[4] =>
[5] =>
[6] => jhjhjh
)
$array = array_map('trim', $array);to$array = array_filter($array, "strlen");? saw this one awhile ago in the php docs to remove space, null, false