views:

59

answers:

3

Right now i'm trying to get this:

Array
(
    [0] => hello
    [1] => 
    [2] => goodbye
)

Where index 1 is the empty string.

$toBeSplit= 'hello,,goodbye';

$textSplitted = preg_split('/[,]+/', $toBeSplit, -1);

$textSplitted looks like this:

Array
(
    [0] => hello
    [1] => goodbye
)

I'm using PHP 5.3.2

+5  A: 

[,]+ means one or more comma characters while as much as possible is matched. Use just /,/ and it works:

$textSplitted = preg_split('/,/', $toBeSplit, -1);

But you don’t even need regular expression:

$textSplitted = explode(',', $toBeSplit);
Gumbo
+1 explode() should outperform preg_split(), plus it doesn't rely on PCRE
Cez
premature optimization. I'm already using preg_ in my code. A little cargo-cultism on my part.
Gutzofter
+1  A: 

How about this:

$textSplitted = preg_split('/,/', $toBeSplit, -1);

Your split regex was grabbing all the commas, not just one.

Mike Pelley
@Mike thats what I get for being a regex cargo-cultist. LOL!
Gutzofter
;o) On another note, Gumbo's pointer to explode in the answer below makes a good point: no need to use a regex for this.
Mike Pelley
A: 

Your pattern splits the text using a sequence of commas as separator (its syntax also isn't perfect, as you're using a character class for no reason), so two (or two hundred) commas count just as one.

Anyway, since your just using a literal character as separator, use explode():

$str = 'hello,,goodbye';

print_r(explode(',', $str));

output:

Array
(
    [0] => hello
    [1] => 
    [2] => goodbye
)
kemp