1

What would be the best way to track changes/additions to a text field? I have a "comments" field for a particular record in the database. What I would like to do is when the user views the record on the website, their original comments appear in plain text. When the supervisor then makes changes/additions, their comments would appear in bold. These comments can happen anywhere in the text. For example:

Original:

These are my comments. They are awesome!

After supervisor comments:

These are my not so great comments. They are awesome! I disagree.

Using MySQL and php, if that matters.

mang
  • 163
  • 1
  • 1
  • 14

1 Answers1

1

You could try out the following code:

function highlight_modified_string($actual_string, $modified_string) {
    $str_array = explode(' ', $actual_string);
    $str_edited_array = explode(' ', $modified_string);
    $str_added = array_diff($str_edited_array, $str_array);

    foreach($str_edited_array as &$str_edited_value) {
        foreach($str_added as $str_added_value) {
            if($str_added_value == $str_edited_value) {
                $str_edited_value = '<span style="font-weight: bold">' . $str_edited_value . '</span>';
            }
        }
        unset($str_edited_value);
    }

    return implode(' ', $str_edited_array);
}

$str = "These are my comments. They are awesome!";
$str_edited = "These are my not so great comments. They are awesome! I disagree.";
$str_modified = highlight_modified_string($str, $str_edited);

echo "<p>{$str}</p>";
echo "<p>{$str_modified}</p>";

I'm not sure if this is what you're looking for. But I've done my best to provide you the solution I could.

Also, this code works with the test case you provided in the question.

But I'm sure this code is not flexible to all the test cases.

Anyway, try your own different test cases to check if the highlight_modified_string function works better.

If you're looking for flexible solution, you can refer to the following post and it has marked answer:

Highlight the difference between two strings in PHP

Community
  • 1
  • 1
Wolverine
  • 1,712
  • 1
  • 15
  • 18
  • Thanks, this should do what I need it to do. I'll just add an extra column called "supervisor comments" and compare the two strings with this. Thank you! – mang Dec 02 '16 at 16:00
  • Did you test it very well? Because it works only with the words added that don't exist in the string. – Wolverine Dec 02 '16 at 16:03