2

Im trying to split string in PHP. I should split string using two delimiters: new line and comma. My code is:

$array = preg_split("/\n|,/", $str)

But i get string split using comma, but not using \n. Why is that? Also , do I have to take into account "\r\n" symbol?

viktor.radovic
  • 498
  • 1
  • 7
  • 18

1 Answers1

8

I can think of two possible reasons that this is happening.

1. You are using a single quoted string:

    $array = preg_split("/\n|,/", 'foo,bar\nbaz');
    print_r($array);

    Array
    (
        [0] => foo
        [1] => bar\nbaz
    )

If so, use double quotes " instead ...

    $array = preg_split("/\n|,/", "foo,bar\nbaz");
    print_r($array);

    Array
    (
        [0] => foo
        [1] => bar
        [2] => baz
    )

2. You have multiple newline sequences and I would recommend using \R if so. This matches any Unicode newline sequence that is in the ASCII range.

    $array = preg_split('/\R|,/', "foo,bar\nbaz\r\nquz");
    print_r($array);

    Array
    (
        [0] => foo
        [1] => bar
        [2] => baz
        [3] => quz
    )
Community
  • 1
  • 1
hwnd
  • 65,661
  • 4
  • 77
  • 114