Skip to content

Instantly share code, notes, and snippets.

@damijanc
Created June 12, 2015 14:30
Show Gist options
  • Save damijanc/ce49bfc64629f293edd9 to your computer and use it in GitHub Desktop.
Save damijanc/ce49bfc64629f293edd9 to your computer and use it in GitHub Desktop.
using unix system to make file diff
/**
* @brief Find the difference between two strings, lines assumed to be separated by "\n|
* @param $new string The new string
* @param $old string The old string
* @return string Human-readable output as produced by the Unix diff command,
* or "No changes" if the strings are the same.
* @throws Exception
*/
public function diff($new, $old)
{
$oldfile = '/tmp/old.txt';
$newfile = '/tmp/new.txt';
if (! file_put_contents($oldfile, $old)) {
throw new \Exception('diff failed to write temporary file: ' .
print_r(error_get_last(), true));
}
if (! file_put_contents($newfile, $new)) {
throw new \Exception('diff failed to write temporary file: ' .
print_r(error_get_last(), true));
}
$answer = array();
$cmd = "diff $newfile $oldfile";
exec($cmd, $answer, $retcode);
unlink($newfile);
unlink($oldfile);
if ($retcode != 0) {
throw new \Exception('diff failed with return code ' . $retcode);
}
if (empty($answer)) {
return 'No changes';
} else {
return implode("\n", $answer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment