Question

I use Linux server for my CakePHP application. I use PHP 5.4.30.
I need to str_replace newlines from a string. I want to use PHP_EOL.

But var_dump(PHP_EOL) gives this:

string(1) " "

It is strange to get empty string for this constant. I was waiting for \n or \r.

This works:

$text=str_replace("\r"," ",$text);

This doesn't work:

$text=str_replace(PHP_EOL," ",$text);

(All my files are UTF8 encoded)

Solution:

str_replace(PHP_EOL..)

didn't work because I get text from a Windows server and process it in Linux server. So Linux's PHP_EOL didn't find the newlines in text. Problem solved when I str_replace both windows and unix newline characters.

Was it helpful?

Solution

Use this:

$text = str_replace(array("\r\n", "\n\r", "\n", "\r"), ' ', $text)

This should cover all the cases regardless of where the system is hosted on.

You can rely on PHP_EOL if all the data is constructed in that OS that is manipulating it, otherwise it is best to use a specific newline character.

OTHER TIPS

You can use PHP_EOL to have a cross-system script working on more systems... but even if it's useful sometime you can find this constant undefined, modern hosting with latest php engine do not have this problem but I think that placing this code in top of your script will save your time spent:

<?php
  if (!defined('PHP_EOL')) {
    if (strtoupper(substr(PHP_OS,0,3) == 'WIN')) {
      define('PHP_EOL',"\r\n");
    } elseif (strtoupper(substr(PHP_OS,0,3) == 'MAC')) {
      define('PHP_EOL',"\r");
    } elseif (strtoupper(substr(PHP_OS,0,3) == 'DAR')) {
      define('PHP_EOL',"\n");
    } else {
      define('PHP_EOL',"\n");
    }
  }
?>

So you can use PHP_EOL without problems... obvious that PHP_EOL should be used on script that should work on more systems that is equivalent to \n or \r or \r\n...

Note about PHP_EOL:

1) on Unix    LN    == \n
2) on Mac     CR    == \r
3) on Windows CR+LN == \r\n

Hope this answer help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top