I have been struggling with the PHP newline character. I agree with the following facts that PHP_EOL provides a platform neutral newline (\r, \r\n, \n based on OS) and we can leverage that to our benefit.
I am doing a simple PHP File Read and Write in my Mac OS (Yosemite) using XAMPP.
Following is my code to write into a file.
$handle = fopen("test.txt", "a+");
$data = "Hello World." . PHP_EOL;
fwrite($handle, $data);
The output in the file is given as follows.
Hello World.\r\n
Note: I had tested this with both fwrite() and file_get_contents(). There is no difference.
My question is : While writing to a file through write with PHP_EOL, why it writes \r\n at the end of the line?
I have not problem in inserting a newline (HTML line break) by invoking nl2br() function. However, due to this character my HTML output has this \r\n characters!!!
I have been playing around with lot of different alternatives as below
$line = str_replace("\r\n","<br/>",$line); // Does NOT work!
$line = preg_replace('~\r?\n~','<br/>', $line); // Works as that of nl2blr()!
$line = str_replace(PHP_EOL, "<br/>",$line); // Works as that of nl2br()!
The options above insert a HTML line break but nothing removes this '\r\n' from the actual text!
I tested by entering few lines manually (obviously there is no \r\n) and this read method works perfectly without any \r\n. Hence, I concluded that {PHP_EOL + file writing method} could be the culprit!
I am really confused about what am I missing?
Any help would be highly appreciated.
Thanks in advance.
Without the double quotes, PHP doesn't process the special character and should replace as you expect.
$line = str_replace('\r\n',"<br/>",$line); // note '\r\n' not "\r\n"