tags:

views:

118

answers:

4

I've got a comma delimited string of id's coming in and I need some quick way to split them into an array. I know that I could hardcode it, but that's just gross and pointless.

I know nothing about regex at all and I can't find a SIMPLE example anywhere on the internet, only huge tutorials trying to teach me how to master regular expressions in 2 hours or something.

fgetcsv is only applicable for a file and str_getcsv is only available in PHP 5.3 and greater.

So, am I going to have to write this by hand or is there something out there that will do it for me? I would prefer a simple regex solution with a little explanation as to why it does what it does.

+7  A: 
$string = "1,3,5,9,11";
$array = explode(',', $string);

See explode()

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter .

Mike B
+1  A: 

Any problem with normal split function?

$array = split(',', 'One,Two,Three');

will give you

Array
(
  [0] => One
  [1] => Two
  [2] => Three
)
S.Mark
Yes. "This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged." per the PHP docs.
Doug Neiner
I see, but his php is < 5.3 anyway (according to this post)
S.Mark
Additionally, it uses a regular expression not a straight string. `explode` uses a straight string and would be faster with less overhead. Unfortunately, because of the way it is named it *seems* like the right function.
Doug Neiner
Thanks dcneiner
S.Mark
+1  A: 

A simple regular expression should do the trick.

$a_ids = preg_split('%,%', $ids);
Alan Storm
Its interesting to see another way to do it, but in this case Regular Expressions are overkill.
Doug Neiner
Fair enough, although its a 6 of one, half dozen the other situation. Performance differences are negligible between the two.
Alan Storm
+1  A: 

If you want to just split on commas:

$values = explode(",", $string);

If you also want to get rid of whitespace around the commas (eg: your string is 1, 3, 5)

$values = preg_split('/\s*,\s*/', $string)

If you want to be able to have commas in your string when surrounded by quotes, (eg: first, "se,cond", third)

$regex = <<<ENDOFREGEX
            /  "  ( (?:[^"\\\\]++|\\\\.)*+ ) \"
             | '  ( (?:[^'\\\\]++|\\\\.)*+ ) \'
             | ,+
            /x
ENDOFREGEX;
$values = preg_split($regex, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
nickf
why the downvote? I'm not repwhoring, but what is wrong with this?
nickf