如何知道源文件是用换行符写的还是用PHP编写的?

时间:2011-03-30 10:37:57

标签: php

如何知道源文件是用换行符还是换行?

我有一个包含文字的文件:

示例:

file1(只能只有一行):

hello stackoverflow hello stackoverflow hello stackoverflow hello stackoverflow hello stackoverflow

file2(可以是多行)

  hello stackoverflow
  hello stackoverflow
  hello stackoverflow
  hello stackoverflow

我们怎么知道在这个文件中是否有换行符或PHP在线;

更新:

<?
$content1 = "lin1 
           lin2";

$content2 = "lin1 lin2";

function file_source_is_new_line($content){
    $data = str_replace(array(chr(13).chr(10),chr(10)),chr(13),$content);
    $matches = count(explode(chr(13),$data));
    echo  count($matches); 
}
file_source_is_new_line($content1);
?>

始终提供1

2 个答案:

答案 0 :(得分:1)

有两种方法:

  • 使用file()功能:

    $lines = count(file('target.php'));
    
  • 自己动手:

    $data = file_get_contents('target.php');
    $data = str_replace(array(chr(13).chr(10),chr(10)),chr(13),$data);
    $lines = count(explode(chr(13),$data));
    

如您所知,行结尾取决于平台; DOS / Win:CRLF,Linux:LF和(旧)OSX:CR。

第一种方法不是跨平台兼容的,而第二种方法是。

但是,函数file()有一些可能对你有用的参数:

  
    

file( filename [, flags ] )

         

filename - 文件的路径。

         

flags - 可选参数标志可以是以下常量中的一个或多个:

         
        
  • FILE_USE_INCLUDE_PATH - 在include_path中搜索文件。

  •     
  • FILE_IGNORE_NEW_LINES - 不要在每个数组元素的末尾添加换行符

  •     
  • FILE_SKIP_EMPTY_LINES - 略读空行

  •     
  

答案 1 :(得分:1)

$fileContents = file_get_contents("test.txt");
preg_match('/.*\n.*/', $fileContents, $matches);
if (count($matches) > 1) { /* Yes, we have new-line in string */ }