1

So, I have two servers (one with Windows OS, and another with Linux), then I have one and the same code which does exactly the same procedure over the same variable with the exact same value. However, on Linux machine this works:

$var = str_replace(PHP_EOL,'', $var);

but on the Windows machine it does not. I expect this code to remove all new blank lines (\n\r or \r\n - I don't remeber the order, but I guess you understand what I mean). So, what I'm doing wrong and how can I fix it?

eisbehr
  • 12,243
  • 7
  • 38
  • 63
Jacobian
  • 10,122
  • 29
  • 128
  • 221
  • Where was $var created? What line endings does it have? If it's exactly the same value on both Linux and Windows, then it will work on one and not the other, because the value of PHP_EOL is different on the two boxes – Mark Baker Dec 18 '15 at 16:54
  • It comes from database. If I copy-paste its contents to MS Word, I see paragraphs symbols inside it. – Jacobian Dec 18 '15 at 16:55
  • `$var = str_replace("\r\n",'', $var);` will only "work" if the line endings in `$var` are `"\r\n"`; if the line endings in `$var` are `"\n"` then nothing will be replaced – Mark Baker Dec 18 '15 at 16:56
  • Thanks! I will check it. – Jacobian Dec 18 '15 at 16:57
  • possible duplicate of http://stackoverflow.com/questions/4975411/when-do-i-use-php-eol-instead-of-n-and-vice-versa-ajax-jquery-client-problem – Funk Forty Niner Dec 18 '15 at 16:59

2 Answers2

4

PHP_EOL is platform-dependent. So it is different in windows and linux.

Moreover it seems you need a way to remove blank lines in a cross-platform way, but using PHP_EOL does not make the code cross-platform, since it depends on what newline-encoding the input file itself uses.

The best way to do this cross-platform is using a regex like /(\r\n)|\r|\n/ to split and/or replace black lines/newlines

$NEWLINE_RE = '/(\r\n)|\r|\n/'; // take care of all possible newline-encodings in input file
$var = preg_replace($NEWLINE_RE,'', $var);
Nikos M.
  • 8,033
  • 4
  • 36
  • 43
  • Well, I've just checked it. For some reason, `str_replace("\r\n",..)` does not work, but preg_replace works. I find it strange. – Jacobian Dec 18 '15 at 17:12
  • it depends on what newline format the file uses (NOT the platform) and also whether the `\r\n` is inside double quotes or single quotes – Nikos M. Dec 18 '15 at 17:13
0

Ran into this issue today. Tried everything I found on this topic plus hints from some other blogs and nothing worked for me.

What finaly did the trick was:

$exploded = explode("\\r\\n", $text);
eisbehr
  • 12,243
  • 7
  • 38
  • 63
Nikolay Shindarov
  • 1,616
  • 2
  • 18
  • 25