$string1 - the first string
$string2 - the second string
$compareCharacters - true to compare characters, and false to compare
lines; this optional parameter defaults to false
$ignoreIndent - false to compare also white spaces in the beginning
on the line, true to ignore them
public static compare ( $string1, $string2, $compareCharacters = false, $ignoreIndent = true ) |
function test_format() { $diff = new Diff(DIFF_SPACE); $one = 'a b c d e f g'; $two = 'a c d e t t f'; $res = $diff->compare($one, $two); $out = $diff->format($res); $expected = array(array('', 'a'), array('-', 'b'), array('', 'c'), array('', 'd'), array('', 'e'), array('+', 't'), array('+', 't'), array('', 'f'), array('-', 'g')); $this->assertEquals($out, $expected); }
function update(Airport $airport) { Diff::compare($airport, Input::all(), function ($key, $value, $model) { $change = new AirportChange(); $change->airport_id = $model->id; $change->user_id = Auth::id(); $change->key = $key; $change->value = $value; $change->save(); }); Messages::success('Thank you for your submission. We will be evaluating your feedback soon.'); return Redirect::route('airport.show', $airport->icao); }
static function checkChangesToFile($snapshot, $filepath) { $lines = array(); if (is_file($filepath)) { $fileNow = FileSystemTools::tail($filepath, 30); if (strlen($fileNow) > 0 && strlen($snapshot) > 0) { $diff = Diff::compare($snapshot, $fileNow); if (count($diff[Diff::INSERTED]) > 0) { foreach ($diff as $dk => $dv) { if ($dv[1] == Diff::INSERTED) { if (strlen(trim($dv[0])) > 0) { $lines[] = $dv[0]; } } } } } } return $lines; }
public function run3() { Qdmvc::loadHelper('class.Diff'); $diff = Diff::compare('Ngay do', 'Ngay mua', true); echo Diff::toHTML($diff, ''); return; foreach ($diff as $item) { if ($item[1] == Diff::DELETED) { echo $item[0]; } } echo '<br>'; foreach ($diff as $item) { if ($item[1] == Diff::INSERTED) { echo $item[0]; } } ?> <?php }
<?php require_once '../diff-lib/Diff.php'; $o = "Привет\nэто\nтекст\nоригинал.\nА это\nудаленная строка\nбыла\nтолько что."; $n = "Привет\nэто\nтекст\nизмененный.\nА это\nбыла\nи новая добавленная\nтолько что."; $diff = Diff::compare($o, $n); ?> <html> <head> <title>Test 3</title> <meta charset="UTF-8"> <link rel="stylesheet" href="../visualization/style.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="../visualization/script.js"></script> </head> <body> <div class="result"> <div class="diff"> <?php echo str_replace('"></p', '"> </p', $diff); ?> </div> </div> </body> </html>
} } ?> </div> <?php if (!empty($oracle_says)) { ?> <div class="row"> <div class="col-md-8 col-md-offset-2"> <span><h3 style="text-align:center">YOU vs. ORACLE</h3></span> <div style="display:table;text-align:left;margin-left:auto;margin-right:auto"> <?php // include the Diff class require_once 'class.Diff.php'; // output the result of comparing two files as a table echo Diff::toTable(Diff::compare(preg_replace('~\\R~u', "\n", empty($expected) ? '' : $expected), $oracle_says)); ?> </div> </div> </div> <?php } ?> <div class="jumbotron" style="height:75%;position:relative;"> <?php if (empty($error)) { ?> <form role="form" id="login-form" action="" method="POST" class="row"> <div class="form-group col-md-6"> <div class="input-group input-group-lg"> <span class="input-group-addon">@</span>
function get_test_result($name, $verbose = false, $moreVerbose = false) { $mergeSpace = IGNORE_INDENT && strpos($name, 'indent.') === false; $path = TEMPLATES_DIRECTORY . DIRECTORY_SEPARATOR . $name; $expectedHtml = @file_get_contents($path . '.html'); if ($expectedHtml === false) { if ($verbose) { echo "! sample for test '{$name}' not found.\n"; } return array(false, array($name, null, "! sample for test '{$name}' not found.\n")); } if ($verbose) { echo "* rendering test '{$name}'\n"; } try { $new = get_php_code($path . '.jade'); } catch (Exception $err) { if ($verbose) { echo "! FATAL: php exception: " . str_replace("\n", "\n\t", $err) . "\n"; } return array(false, array($name, null, "! FATAL: php exception: " . str_replace("\n", "\n\t", $err) . "\n")); } if (is_null($new)) { return array(false, array($name, null, "! FATAL: " . $path . ".jade returns null\n")); } $actualHtml = get_generated_html($new); $from = array("'", "\r", "<!DOCTYPEhtml>"); $to = array('"', '', ''); if ($mergeSpace) { array_push($from, "\n", "\t", " "); array_push($to, '', '', ''); } $expectedHtml = preg_replace_callback('`class\\s*=\\s*(["\'])([^"\']+)\\1`', 'orderWords', $expectedHtml); $actualHtml = preg_replace_callback('`class\\s*=\\s*(["\'])([^"\']+)\\1`', 'orderWords', $actualHtml); if ($mergeSpace) { $expectedHtml = preg_replace('`(?<=[\'"])\\s(?=>)|(?<=[a-zA-Z0-9:])\\s(?=(>|\\s[a-zA-Z0-9:]))`', '', $expectedHtml); $actualHtml = preg_replace('`(?<=[\'"])\\s(?=>)|(?<=[a-zA-Z0-9:])\\s(?=(>|\\s[a-zA-Z0-9:]))`', '', $actualHtml); } $minifiedExpectedHtml = str_replace($from, $to, trim($expectedHtml)); $minifiedActualHtml = str_replace($from, $to, trim($actualHtml)); $result = array($name, $minifiedExpectedHtml, $minifiedActualHtml); if (strcmp($minifiedExpectedHtml, $minifiedActualHtml)) { if ($verbose) { include_once __DIR__ . '/diff.php'; $actualHtml = preg_replace('`(\\r\\n|\\r|\\n)([\\t ]*(\\r\\n|\\r|\\n))+`', "\n", $actualHtml); $expectedHtml = preg_replace('`(\\r\\n|\\r|\\n)([\\t ]*(\\r\\n|\\r|\\n))+`', "\n", $expectedHtml); echo Diff::toString(Diff::compare($expectedHtml, $actualHtml)) . "\n"; /* echo " Expected: $expectedHtml\n"; echo " Actual : $actualHtml\n\n"; */ } if ($moreVerbose) { echo " PHP : " . compile_php($name); } return array(false, $result); } return array(true, $result); }
public function getDiff() { $fileNew = realpath($this->getFile()); $fileOld = dirname(__DIR__) . '/../addons/files/local/' . $this->aid . '.zip'; if (!is_file($fileOld)) { $path = realpath(dirname(__DIR__) . '/../addons/files/local/'); $fh = fopen($path . '/' . $this->aid . '.zip', 'w'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://" . AWSFileManager::getBucket() . "/addons/" . $this->aid . "_1"); curl_setopt($ch, CURLOPT_FILE, $fh); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // this will follow redirects curl_exec($ch); curl_close($ch); fclose($fh); } $fileOld = realpath(dirname(__DIR__) . '/../addons/files/local/' . $this->aid . '.zip'); $zipNew = new ZipArchive(); $zipOld = new ZipArchive(); $resNew = $zipNew->open($fileNew); $resOld = $zipOld->open($fileOld); if ($resNew === TRUE && $resOld === TRUE) { $newFiles = array(); for ($i = 0; $i < $zipNew->numFiles; $i++) { $newFiles[] = $zipNew->getNameIndex($i); } $oldFiles = []; for ($i = 0; $i < $zipOld->numFiles; $i++) { $oldFiles[] = $zipOld->getNameIndex($i); } $added = array_diff($newFiles, $oldFiles); $removed = array_diff($oldFiles, $newFiles, ["glass.json", "version.json"]); $commonFiles = array_intersect($newFiles, $oldFiles); $commonFiles = array_diff($commonFiles, ["glass.json", "version.json"]); $diff = []; foreach ($commonFiles as $fi) { if (strpos($fi, ".cs") == strlen($fi) - 3) { $newStr = $zipNew->getFromName($fi); $oldStr = $zipOld->getFromName($fi); if (trim($newStr) != trim($oldStr)) { $diff[$fi] = Diff::toTable(Diff::compare($oldStr, $newStr)); } } } $ret = ["added" => $added, "removed" => $removed, "changes" => $diff]; return $ret; } else { return false; } }
public static function diff($text1, $text2) { $diff = new Diff(); return $diff->compare($text1, $text2); }
<?php // include the Diff class require_once './class.Diff.php'; // compare two strings character by character $diff = Diff::compare('abcmnz', 'abcmnz', true); var_dump($diff);
<?php $input_array = array('id' => $args['content']->id); $before = build_field_content_blockquote($input_array); $input_array = array('id' => $args['content']->parent); $after = build_field_content_blockquote($input_array); foreach ($before as $key => $val) { ?> <blockquote class="content_field_blockquote"> <div class="content_field"> <label><?php echo $val['field_name']; ?> </label> <div class="content_field_value"> <?php $before_val = $val['field_val']; $after_val = $after[$key]['field_val']; echo Diff::toTable(Diff::compare($before_val, $after_val)); ?> </div> </div> </blockquote> <?php } ?> </div> </div>
function wiki_compare_page($arr) { $pageUrlName = array_key_exists('pageUrlName', $arr) ? $arr['pageUrlName'] : ''; $resource_id = array_key_exists('resource_id', $arr) ? $arr['resource_id'] : ''; $currentCommit = array_key_exists('currentCommit', $arr) ? $arr['currentCommit'] : 'HEAD'; $compareCommit = array_key_exists('compareCommit', $arr) ? $arr['compareCommit'] : null; if (!$compareCommit) { return array('message' => 'No compare commit was provided', 'success' => false); } $w = wiki_get_wiki($resource_id); if (!$w['path']) { return array('message' => 'Error reading wiki', 'success' => false); } $page_path = $w['path'] . '/' . $pageUrlName . '.md'; if (is_readable($page_path) === true) { $reponame = array_key_exists('title', $w['wiki']) ? urlencode($w['wiki']['title']) : 'repo'; if ($reponame === '') { $reponame = 'repo'; } $git = new GitRepo('', null, false, $w['wiki']['title'], $w['path']); $compareContent = $currentContent = ''; try { foreach ($git->git->tree($currentCommit) as $object) { if ($object['type'] == 'blob' && $object['file'] === $pageUrlName . '.md') { $currentContent = $git->git->cat->blob($object['hash']); } } foreach ($git->git->tree($compareCommit) as $object) { if ($object['type'] == 'blob' && $object['file'] === $pageUrlName . '.md') { $compareContent = $git->git->cat->blob($object['hash']); } } require_once 'library/class.Diff.php'; $diff = Diff::toTable(Diff::compare($currentContent, $compareContent)); } catch (\PHPGit\Exception\GitException $e) { return array('message' => 'GitRepo error thrown', 'success' => false); } return array('diff' => $diff, 'message' => '', 'success' => true); } else { return array('message' => 'Page file not writable', 'success' => false); } }
/** * Returns a comparison of the two specified versions of the specified item * in the form of an associative array. * * @param string name of collection * @param string name of unique id column * @param mixed unique id of item * @param integer unique revision id of newer version * @param integer unique revision id of older version * @return array hash * */ function compare($collection, $key, $id, $rid1, $rid2, $diff_type = DIFF_HTML) { // returns diff as associative array $rev1 = $this->getRevision($collection, $key, $id, $rid1, true); if (!is_object($rev1)) { $this->error = 'Revision #' . $rid1 . ' does not exist.'; return false; } $rev2 = $this->getRevision($collection, $key, $id, $rid2, true); if (!is_object($rev2)) { $this->error = 'Revision #' . $rid2 . ' does not exists.'; return false; } $diff = new Diff(DIFF_HTML); $out = array(); foreach (array_keys(get_object_vars($rev1)) as $key) { $out[$key] = $diff->format($diff->compare($rev1->{$key}, $rev2->{$key})); } return $out; }
public function diff($snapshotId1, $snapshotId2) { $x = Snapshot::find($snapshotId1)->readNoTags(); $y = Snapshot::find($snapshotId2)->readNoTags(); $html = "<style>\n \t\t.diffInserted{\n \t\t\tborder: 1px solid rgb(192,255,192);\n \t\t\tbackground: rgb(224,255,224);\n \t\t}\n \t\t.diffDeleted{\n \t\t\tborder: 1px solid rgb(255,192,192);\n \t\t\tbackground: rgb(255,224,224);\n \t\t}\n \t</style>"; return $html . Diff::toTable(Diff::compare($x, $y)); }