How to break a line that ends with a line break. I tried explode('\n', $str) - failed.

  • one
    change \ n to \ r \ n - G.Denis
  • 3
    It does not work, it turned out to substitute PHP_EOL - quaresma89
  • one
    Maybe the fact is that you need to \ n enclose in double quotes? - "\ n" - Bookin

2 answers 2

I tried explode('\n', $str)

For such cases it is better to use preg_split . Specifying "/\n/" , the regular itself will determine, depending on the OS, which sequence of characters to consider the new line.

    First, "\n" (and other similar characters) must be enclosed in double quotes, otherwise php "sees" not a newline, but two characters: "\" and the letter "n" .

    Secondly, in different operating systems, newline characters may differ: In Windows, "\r\n" , in Unixes, "\n" , etc .; therefore, it is better to use the PHP_EOL constant.

    Thirdly, if you need to get a file in the form of an array, then there is a remarkable function file()

    • 1) Double quotes activate line interpolation. It sounds smarter :) 2) \n is there and there. The problem is in the first paragraph. - user207618