1

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
)
2
  • Just use preg_split(). Once you start using regular expressions you'll never turn back. Commented Feb 15, 2016 at 21:09
  • what bout replacing $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 Commented Feb 15, 2016 at 21:35

3 Answers 3

11

You can solve your problem and simplify the code by using preg_split(). You can apply a regex including all delimiters in a character class with a quantifier and \s* to consume whitespaces around the delimiters.

Code:

$array = preg_split("/\s*[" . preg_quote(implode("", $delimiters), "/") . "]+\s*/", $str);
                      └┬┘└────────────────────────┬─────────────────────────┘└┬┘ 
      Consuming any whitespaces                   │             Consuming any whitespaces 
      around delimiter                            │             around delimiter
                                   ┌──────────────┘
                                   ├ []           → Character class with quantifier
                                   ├ implode()    → Converting array into a string
                                   └ preg_quote() → Escaping special characters
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent RR! I was headed for the bull-in-a-China-shop approach with preg_replace() then explode() like this $foo_array = explode(' ', preg_replace('/\s{2,}/', ' ', $str));
When imploding with an empty string as the glue, the glue parameter can be omitted.
2

You can also use :

array_filter($tagsArray);

Or use :

array_diff( $tagsArray, array( '' ));

1 Comment

Nice simple approach!
0

There is already a working preg_split() answer, but maybe more flexible to just use PREG_SPLIT_NO_EMPTY:

$tagsArray = preg_split('/[ ,]/', $tagsString, null, PREG_SPLIT_NO_EMPTY);  // or '/ |,/'

2 Comments

Would this limit to just 1 type of delimiter though?
No. The code uses spaces and commas and you can add whatever you want either separated by the OR | operator or in a character class [].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.