我有一个员工用来添加评论和其他信息的数据库。注释可能会变得相当长,我想知道是否有方法可以只获取更改的文本。
示例:
$before_text = "This is a long piece of text where the employee has made a comment about the STARTER of their project. Notes and information go here, blah, blah, blah...";
$after_text = "This is a long piece of text where the employee has made a comment about the STATUS of their project. Notes and information go here, blah, blah, blah...";
当我比较这两个变量时,我得到的事实是文本已经从$before_text
更改为$after_text
,但我想以下面这样的变量结束:
$change = "'STARTER' changed to 'STATUS'";
..。这样我就可以把它写进日志了。其中一些注释非常长,我不得不写一个日志,其中有两个很大的条目来描述发生了什么变化。
有没有办法只提取在两个文本/字符串变量之间发生变化的文本?
发布于 2017-09-18 16:54:12
我希望您能够展示$before_text
和$after_text
之间的区别
<?php
$string_old = "hello this is a demo page";
$string_new = "hello this is a beta page";
$diff = get_decorated_diff($string_old, $string_new);
echo "<table>
<tr>
<td>".$diff['old']."</td>
</tr>
<tr>
<td>".$diff['new']."</td>
</tr>
</table>";
,这里是函数'get_decorated_diff'
function get_decorated_diff($old, $new){
$from_start = strspn($old ^ $new, "\0");
$from_end = strspn(strrev($old) ^ strrev($new), "\0");
$old_end = strlen($old) - $from_end;
$new_end = strlen($new) - $from_end;
$start = substr($new, 0, $from_start);
$end = substr($new, $new_end);
$new_diff = substr($new, $from_start, $new_end - $from_start);
$old_diff = substr($old, $from_start, $old_end - $from_start);
$new = "$start<ins style='background-color:#ccffcc'>$new_diff</ins>$end";
$old = "$start<del style='background-color:#ffcccc'>$old_diff</del>$end";
return array("old"=>$old, "new"=>$new);
}
它将返回以下内容
但是当有多个变化的时候..这可能很复杂!
发布于 2017-09-18 16:42:32
这里有一些quick & dirty可以帮你入门。我为每个项目创建了一个数组,对该数组进行差分以获得新值,然后使用新值的索引来获得新值。
$before_text = "This is a long piece of text where the employee has made a comment about the STARTER of their project. Notes and information go here, blah, blah, blah...";
$after_text = "This is a long piece of text where the employee has made a comment about the STATUS of their project. Notes and information go here, blah, blah, blah...";
$arr1 = explode(' ', $before_text);
$arr2 = explode(' ', $after_text);
$diff = array_diff($arr1, $arr2);
print_r($diff);
$new = $arr2[key($diff)];
echo $new;
这将返回:
Array
(
[16] => STARTER
)
STATUS
但这里有一个警示故事:如果用户更改了多个单词或做了一些其他奇怪的事情,您将不得不进行一些循环和排序,以使其接近正确。YMMV
https://stackoverflow.com/questions/46283871
复制