views:

88

answers:

3

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($file2);
if (strcmp($content, $content2) == 0) { etc;
+5  A: 

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.

Veeti
A: 
preg_replace('/\v+/','\n',$text1)==preg_replace('/\v+/','\n',$text2)
stillstanding
+1  A: 

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.

Pekka