开发者

How to know the source file is write in newline or a line in PHP?

How to know the source file is write in newline or a line?

I have a file that contains the text:

example:

file1(can be just only one line) :

hello stackoverflow hello stackoverflow hello stackoverflow hello stackoverflow hello stackoverflow

file2(can be multiple line)

  hello stackoverflow
  hello stackoverflow
  hello stackoverflow
  hello stackoverflow

How Can we know that in this file Are there the newline or online with PHP;

UPDATE:

<?
$conten开发者_如何学Got1 = "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);
?>

Always give 1 ?


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


There are two ways:

  • Using file() function:

    $lines = count(file('target.php'));
    
  • Doing it yourself:

    $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));
    

As you may know, line endings are platform dependent; DOS/Win: CRLF, Linux: LF and (old) OSX: CR.

The first method is not cross-platform compatible, while the second one is.

However, the function file() has some arguments which might be useful to you:

file( filename [, flags ] )

filename - Path to the file.

flags - The optional parameter flags can be one, or more, of the following constants:

  • FILE_USE_INCLUDE_PATH - Search for the file in the include_path.

  • FILE_IGNORE_NEW_LINES - Do not add newline at the end of each array element

  • FILE_SKIP_EMPTY_LINES - Skip empty lines

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜