Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare 2 strings and display difference (php or javascript)

Comparing must work on-the-fly, so this must be done via javascript or with php (will make javascript ajax request).

What I need is probably advanced difference showing, so it will be probably best if there is any kind of good supported library.

This picture shows exactly what I need >

Tortoise Merge

Added #1: I found this http://ejohn.org/projects/javascript-diff-algorithm/ (example http://www.djsipe.com/js-diff/) which is ok, but doesn't support multiline? and it changes the whole word when only one character is different...

Added #2: I tested php script ( https://github.com/paulgb/simplediff/ ) but it has flaws.

Added #3: I found what i was looking for ( http://code.google.com/p/google-diff-match-patch/ )

like image 647
Glavić Avatar asked Jan 05 '11 22:01

Glavić


People also ask

Can we compare two strings in JavaScript?

The localeCompare() method compares two strings in the current locale. The localeCompare() method returns sort order -1, 1, or 0 (for before, after, or equal).

Can you use == to compare strings in PHP?

The assignment operator assigns the variable on the left to have a new value as the variable on right, while the equal operator == tests for equality and returns true or false as per the comparison results. Example: This example describes the string comparison using the == operator.

Can you compare strings in PHP?

The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().

Can you use == to compare strings in JavaScript?

Explanation of the example: In the above example, when str1 and str2 are compared after using the toUpperCase method, the expression JAVASCRIPT == JAVASCRIPT would return true as they are the same strings after both being in upper case. Here, the equality operator (==) is used to check if both the strings are the same.


1 Answers

This answer to a related question seems promising for javascript. google-diff-match-patch

It provides an API which will take care of all the complex and well known algorithms. However you'll have to do some work with the presentation.

PHP is more versatile there is a lot of diff tools out there. Look this other related question Calculate text diffs in PHP.

like image 174
mmarinero Avatar answered Sep 30 '22 09:09

mmarinero