开发者

How do you compare two text files with different line endings in PHP?

开发者 https://www.devze.com 2023-01-11 10:05 出处:网络
I need to compare two text files in php. One file is user uploaded, and the other is supplied by the server, running on windows.

I need to compare two text files in php. One file is user uploaded, and the other is supplied by the server, running on windows. This works fine when the file is submitted from another windows computer, but from a linux computer the files come out different, I am assuming this is because of different line endings. Is there an easy way to compare windows text files to linux text files?

Currently this is my code;

$text1 = file_get_contents($file1);
$text2 = file_get_contents($fil开发者_运维百科e2);
if (strcmp($content, $content2) == 0) { etc;


You could replace CRLF line endings with LF line endings or the other way around in both files - try something like this:

$text1 = str_replace("\r\n", "\n", $text1)

And the same for $text2.


Just to add another, potentially more portable option (the replacing suggested by the other answerers will already fine for your the case), the file() function splits file data into an array and seems to be able to handle both Windows and Linux encodings:

$text1 = file($file1, FILE_IGNORE_NEW_LINES);
$text2 = file($file2, FILE_IGNORE_NEW_LINES);  

if ($text1 === $text2) .... 

It can also deal with Macintosh line endings if the auto_detect_line_endings runtime setting is turned on.


preg_replace('/\v+/','\n',$text1)==preg_replace('/\v+/','\n',$text2)
0

精彩评论

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