Returns the diff between two arrays or strings as array.
every array-entry containts two elements:
array|string $from:
array|string $to:
array
public static function diffToArray($from, $to) {
preg_match_all('(\\r\\n|\\r|\\n)', $from, $fromMatches);
preg_match_all('(\\r\\n|\\r|\\n)', $to, $toMatches);
if (is_string($from)) {
$from = preg_split('(\\r\\n|\\r|\\n)', $from);
}
if (is_string($to)) {
$to = preg_split('(\\r\\n|\\r|\\n)', $to);
}
$start = array();
$end = array();
$fromLength = count($from);
$toLength = count($to);
$length = min($fromLength, $toLength);
for ($i = 0; $i < $length; ++$i) {
if ($from[$i] === $to[$i]) {
$start[] = $from[$i];
unset($from[$i], $to[$i]);
}
else {
break;
}
}
$length -= $i;
for ($i = 1; $i < $length; ++$i) {
if ($from[$fromLength - $i] === $to[$toLength - $i]) {
array_unshift($end, $from[$fromLength - $i]);
unset($from[$fromLength - $i], $to[$toLength - $i]);
}
else {
break;
}
}
$common = self::longestCommonSubsequence(array_values($from), array_values($to));
$diff = array();
$line = 0;
if (isset($fromMatches[0]) && $toMatches[0] && count($fromMatches[0]) === count($toMatches[0]) && $fromMatches[0] !== $toMatches[0]) {
$diff[] = array(
'#Warning: Strings contain different line endings!',
0,
);
}
foreach ($start as $token) {
$diff[] = array(
$token,
0,
);
}
reset($from);
reset($to);
foreach ($common as $token) {
while (($fromToken = reset($from)) !== $token) {
$diff[] = array(
array_shift($from),
2,
);
}
while (($toToken = reset($to)) !== $token) {
$diff[] = array(
array_shift($to),
1,
);
}
$diff[] = array(
$token,
0,
);
array_shift($from);
array_shift($to);
}
while (($token = array_shift($from)) !== NULL) {
$diff[] = array(
$token,
2,
);
}
while (($token = array_shift($to)) !== NULL) {
$diff[] = array(
$token,
1,
);
}
foreach ($end as $token) {
$diff[] = array(
$token,
0,
);
}
return $diff;
}