views:

22

answers:

3

I'm wondering a good way of splitting strings by a | delimiter if the input strings could be of the following form:

"foo,    bar"
"foo       ,bar"
"foo,bar"
"foo , bar"
"foo bar"
"foo,,bar"

So the only possible outputs strings are as:

"foo|bar"
"foo|bar|other|here"

Independently of how many terms are within the input string.

Any thoughts would be appreciated!

+2  A: 
preg_replace('/\s*,\s*/', '|', $string);

This will handle the cases with the comma ;) If you need the one with only the whitespace too:

preg_replace('\s*,\s*|\s+', '|', $string);
nikic
A: 

Something like this should do the trick...

$outputstring = preg_replace_all('/\b[ ,|]+\b/','|',$inputstring);

to explain:

\b is a word-boundary, so it is looking for any combination of spaces, commas or pipes between two word boundaries.

Spudley
This will match `foo,,,bar, , , , , foo`, too.
nikic
@nick -- true. but the questioner didn't specify what to do with multiple commas; in fact, I read his last example a implying to ignore them.
Spudley
@Spudley: This last example wasn't there when I wrote my answer and this comment. After the change your response is obviously correct. (Why doesn't stackoverflow show all edits any more?)
nikic
Ah, got it. There is a 5 minute grace period in which edits aren't logged ;)
nikic
+1  A: 

I would do:

    $input = preg_replace('/[ ,]+/', '|', $input);
codaddict
this will allow `foo,,,,,bar`, too.
nikic