14

Possible Duplicate:
How to split a string by multiple delimiters in PHP?

What would be the most efficient way to split a string by three delimiters at the same time, specifically a single white space, newline, and commas?

Community
  • 1
  • 1
Michael Staudt
  • 327
  • 2
  • 5
  • 13

1 Answers1

23

Since you've tagged your questions with php I will stick to that. See preg_split

$split_strings = preg_split('/[\ \n\,]+/', $your_string);

This will keep the array clean too, in case your string is something like some, ,,string, it will still result in ['some', 'string'] instead of ['some', '', '', '', 'string'].

deefour
  • 34,974
  • 7
  • 97
  • 90
  • What about incorporating an escape character? `hey 'this is' some text` yielding `['hey', 'this is', 'some', 'text']`? – Nick Strupat Jan 23 '14 at 21:01
  • Depending on the operating system it can be useful to add the return character, so it would be like $split_strings = preg_split('/[\ \n\r\,]+/', $your_string); (added \r after \n) – Unapedra Jan 14 '16 at 15:25
  • 1
    Also, to avoid "empty strings" to be returned on the array, you should use `PREG_SPLIT_NO_EMPTY` on the flags parameter, so it would be like `preg_split('/[\ \n\r\,]+/', $your_string, -1, PREG_SPLIT_NO_EMPTY);`, as told in: http://php.net/manual/en/function.preg-split.php – Unapedra Jan 14 '16 at 16:33
  • Why note `explode(' ', $my_string)`? – serraosays Mar 15 '19 at 02:32