I know this has been answered, but, you could do this with one command:
$input = "foo, bar, baz., shibby, poop.";
//-- handles it all in one pass
$output = preg_split('/[\.,\s]/', $input, -1, PREG_SPLIT_NO_EMPTY);
//-- just output
array_walk($output, function(&$item, $idx) {
echo $idx . ': ' . $item . PHP_EOL;
});
If you're expecting spaces in your values, however, this will split them up too. I just added \s
to the regex to trim the elements. If you expect spaces in values, then omit the \s
in the regex and trim()
the elements later.
Or, this regex will produce the same: /(\.\s?|,\s?)/
$input = "foo, bar, baz., shibby, poop. foo bar";
//-- handles it all in one pass
$output = preg_split('/(\.\s?|,\s?)/', $input, -1, PREG_SPLIT_NO_EMPTY);
//-- just output
array_walk($output, function(&$item, $idx) {
echo $idx . ': ' . $item . PHP_EOL;
});
Produces
0: foo
1: bar
2: baz
3: shibby
4: poop
5: foo bar
The Regex: explained
The original regex simply split on single characters in the string as denoted by the [
and ]
. Thus, /[\.,\s]/
matches on period, comma, AND space characters in the string. After thinking about it, this is probably not what you want but close.
The updated regex is a little different and splits on two different scenarios. \.\s?
says: split on the period and/or preiod+space. The ?
makes the preceding optional (I believe 0 or 1). Same with the ,\s?
. Match on comma and/or comma+space. This accounts for all the scenarios. Using grouping ((...)
) instead of character ranges allows for this. The pipe |
in the middle means OR so, the complete regex means: match on period and/or period+space OR comma and/or comma+space.