/**
* @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 static function diff($new, $old) {
$tempdir = '/var/somewhere/tmp'; // Your favourite temporary directory
$oldfile = tempnam($tempdir,'OLD');
$newfile = tempnam($tempdir,'NEW');
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 != 1) {
throw new Exception('diff failed with return code ' . $retcode);
}
if (empty($answer)) {
return 'No changes';
} else {
return implode("\n", $answer);
}
}
$old_data = "We'll of today's hunt we will find inner zen. You are awesome [TEAM_NAME]! Cleveland has a lot more to offer though, so keep on roaming and find some happiness with Let's Roam!;";
$new_data = "We'll of today's hunt we will find inner zen. Great job today, you are freaking super awesome [TEAM_NAME]! though, so keep roaming Cleveland has a lot more to offer and find happiness on www.letsroam.com!;";
if($old_data) {
$old_words = explode(" " , $old_data);
$new_words = explode(" ", $new_data);
$added_words = array();
$deleted_words = array();
$unchanged_words = array();
foreach($new_words as $new_word) {
$new_word_index = array_search($new_word, $old_words);
// if($new_word == "you"){
// die_r(array());
// }
if( $new_word_index > -1) {
// word already exists
array_push($unchanged_words, $new_word);
unset($old_words[$new_word_index]);
} else {
// word does not already exists
array_push($added_words, $new_word);
}
}
$deleted_words = $old_words;
$added_word_count = count($added_words);
$added_word_characters = strlen(implode(" ", $added_words));
}
die_r(array(
"old_data"=> $old_data,
"new_data"=> $new_data,
"unchanged_words"=> $unchanged_words,
"added_words"=> $added_words,
"deleted_words"=> $deleted_words,
"added_word_count"=>$added_word_count,
"added_word_characters"=>$added_word_characters
));