This PHP function compares just the text in two files. It’s useful if you need to check whether the files contain the same text, regardless of line breaks, new lines, carriage returns, or extra spaces.
/** * Compare 2 text files to see if just the text is the same. * Removes all linebreaks and extra spaces at ends of sentences * so as to compare just the text. * * @return bool True if the text is the same in both files, otherwise false. */ function are_files_text_same($file1, $file2) { $t = array(); foreach (array($file1, $file2) as $f) { $fh = fopen($f, "r"); $string = fread($fh, filesize($f)); fclose($fh); $string = trim($string); $string = trim(preg_replace('/\s\s+/', ' ', $string)); $t[] = preg_replace( '/([\r\n\t])/', "", $string ); } return ($t[0] == $t[1]); }
Usage Example
$file1 = '/var/www/some-file.txt'; $file2 = '/var/www/other-file.txt'; $same = are_files_text_same($file1, $file2); echo ($same) ? "Success, '$file1' is the same as '$file2'" : "Fail, '$file1' is NOT the same as '$file2'";
Questions and Comments are Welcome