PHP_EOL 用法 : Most Worthless Constant?

PHP_EOL may very well be the most worthless general-purpose constant in modern PHP. It's supposed to be helpful for cross-platform developing, for example you could write a PHP-powered shell script that says:

<?php
echo "Operation Successful!" . PHP_EOL;

 

and then expect the proper newline to terminate the output string based on the platform PHP is running on.

That's all well and good, but the following is functionally equivalent:

<?php
echo "Operation Successful!\n";

 

Try it out and you'll see. In console output on Windows, Linux, and Mac they all are displayed with the expect newline terminating the output string.

 

I don't see it being useful for writing data or log output to a file either. If you're writing and reading on the same platform then newline discrepancies won't be an issue, and if you're writing on one platform and reading on another then you'll want to standardize on a newline anyway.

 

Has PHP_EOL's time come and gone? Do you use it in your code, and if so why?

 

from: http://zaemis.blogspot.com/2012/09/phpeol-most-worthless-php-constant.html

 

一个小小的换行,其实在不同的平台有着不同的实现,为什么要这样,可以是世界是多样的。

回车换行其实是两个符号

 

\r 回车  //回到行首   return

\n换行   //重新换一行 newline

 

一般情况下\n和\r\n是没有区别的,因为一般情况下,下一行是空白的,没有内容的,但是如果下一行有内容,那么两者的不同就会体现出来,\r\n光标会显示在新行的行首,而\n的光标则会显示在新行的字符结尾处

 

本来在unix世界换行就用\n来代替,但是windows为了体现他的不同,就用\r\n,更有意思的是在mac中用\r

因此unix系列用 \n

windows系列用 \r\n

mac用 \r

 

这样就用你写的程序在不同的平台上运行有着不少的麻烦

比如有的程序要把文件中的所有行都合成一行,这有不同的实现方式,

 

第一种方式

str_replace(array("\r","\n","\r\n"),"",$string);

 

 

第二种方式就用正则表达示

$str = preg_replace('/\s*/', '', $str);

 

第三种方式

这里不得不重新看一下php 那些已经定义好的变量

PHP_EOL 就是其中的一个,代表php 的换行符,这个变量会根据平台而变,在windows下会是\r\n,在linux下是\n,在mac下是\r

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

 

 

来源: http://blog.sina.com.cn/s/blog_6dbaeb9b0100z4tt.html

 

 

你可能感兴趣的:(Const)