1

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!

3 Answers 3

2
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);
Sign up to request clarification or add additional context in comments.

Comments

1

I would do:

    $input = preg_replace('/[ ,]+/', '|', $input);

1 Comment

this will allow foo,,,,,bar, too.
0

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.

4 Comments

This will match foo,,,bar, , , , , foo, too.
@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.
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?)
Ah, got it. There is a 5 minute grace period in which edits aren't logged ;)

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.