Skip to content

Instantly share code, notes, and snippets.

@halfcoder
Created February 2, 2014 02:57
Show Gist options
  • Save halfcoder/8762410 to your computer and use it in GitHub Desktop.
Save halfcoder/8762410 to your computer and use it in GitHub Desktop.
文本比较结果显示的PHP代码片段
<?php
/**
* 构造文本比较的显示结果的函数
*
* @version 0.1
* @param array $changes 比较得到的改动的集合
* @param array $base_content 基准内容按行分隔得到的数组
* @param array $changed_content 修订内容按行分隔得到的数组
* @return array 构造显示结果的集合,每个元素为array(改动类型或者"skip", 基准内容中的行号, 基准内容中的行的内容, 修订内容中的行号, 修订内容中的行的内容)
*/
function viewdiff($changes, $base_content, $changed_content) {
$changes_count = count($changes);
$base_content_length = count($base_content);
$changed_content_length = count($changed_content);
$viewdata = array();
for($i = 1; $i <= $changes_count; $i++) {
if($changes[$i][0] === '-') {
for($j = -3, $k = -2; $j <= 3 && $k <= 4;) {
if($changes[$i][1] + $j < 0) {
$j++;
$k++;
continue;
}
else if($changes[$i][1] + $j >= $changed_content_length) {
break;
}
else if($j === 0){
$viewdata[] = array('deleted', $changes[$i][1] + 1,
htmlspecialchars($base_content[$changes[$i][1]]), '', '');
$j++;
}
else {
$viewdata[] = array('same', $changes[$i][1] + 1 + $j,
htmlspecialchars($base_content[$changes[$i][1] + $j]), $changes[$i][2] + 1 + $k,
htmlspecialchars($changed_content[$changes[$i][2] + $k]));
$j++;
$k++;
}
}
}
else if($changes[$i][0] === '+') {
for($j = -2, $k = -3; $j <= 4 && $k <= 3;) {
if($changes[$i][1] + $k < 0) {
$j++;
$k++;
continue;
}
else if($changes[$i][1] + $k >= $base_content_length) {
break;
}
else if($k === 0){
$viewdata[] = array('added', '', '', $changes[$i][2] + 1,
htmlspecialchars($changed_content[$changes[$i][2]]));
$k++;
}
else {
$viewdata[] = array('same', $changes[$i][1] + 1 + $j,
htmlspecialchars($base_content[$changes[$i][1] + $j]), $changes[$i][2] + 1 + $k,
htmlspecialchars($changed_content[$changes[$i][2] + $k]));
$j++;
$k++;
}
}
}
else {
for($j = -3; $j <= 3;) {
if($changes[$i][1] + $j < 0 || $changes[$i][2] + $j < 0) {
$j++;
continue;
}
else if($changes[$i][1] + $j >= $base_content_length || $changes[$i][2] + $j >= $changed_content_length) {
break;
}
else {
$viewdata[] = array($j === 0 ? 'changed' : 'same', $changes[$i][1] + 1 + $j,
htmlspecialchars($base_content[$changes[$i][1] + $j]), $changes[$i][2] + 1 + $j,
htmlspecialchars($changed_content[$changes[$i][2] + $j]));
$j++;
}
}
}
if($i !== $changes_count) {
$viewdata[] = array('skip', '...', '', '...', '');
}
}
return $viewdata;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment