MySQL仅获取已更改的特定文本字符串

时间:2017-09-18 16:11:11

标签: php mysql

我有一个员工用来添加评论的数据库以及其他信息。评论可能会变得很长,我想知道是否有办法只获得改变的文字。

示例:

$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'"; 

...这样我就可以将它放入日志中。其中一些评论很长,我不得不最终得到一个日志,其中有两个大的条目来描述发生了什么变化。

有没有办法只提取两个文本/字符串变量之间发生变化的文本?

2 个答案:

答案 0 :(得分:1)

以下内容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

答案 1 :(得分:1)

希望您尝试在$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);
}

将返回以下内容

enter image description here

但是当多次改变时......它可能很复杂!