View Full Version : file comparison - diffs

12-09-2003, 07:27 PM
I'm attempting to write a function that will compare 2 input files line by line and output the differences as a readable page, with blocks of different lines outlined and displayed twice.. and the blocks that are the same displayed only once.. I've managed to get it to compare each line and output the differences, however i can't figure out how to find where the differences end.. IE it works fine if only one line is changed. however if i add an extra line to file 1, each line after that is shown as changed, when it really isn't. I'll be glad to provide more details if this doesn't make sense, but any help here would be greatly appreciated.

12-09-2003, 10:47 PM
hmm it seems simple enough, you just read each file into the array and use strcmp() to see if they are the same, if they're different then you output both strings, if not then you output one and then the loop just goes onto the next line.

Where is it that you are having trouble? fancy posting some example code?

12-09-2003, 11:11 PM
yeah, i've got it as far as what you mentioned, however i'm running into problems if the changes involve more than one line.. if file 1 is a 10 line file and file 2 is that same as file one except with a new line inserted at line 5, the line by line comparison thinks that all the rest of the lines are off. what i need is a way to check forward in both files to find a place where the contents start to match up again, output differing blocks of text. I'd include some code but all i've got is what you just described.. something like this:

while($x<= $highest_line_number){

if (!($contents[0][$x] == $contents[1][$x])){
echo "mismatch line $x<br>";

12-10-2003, 03:28 AM
first off , I personally hate it when someone says 'theres no need to reinvent the wheel'

however ... in this case , unless this is just a project .. perhaps theres no need to reinv.. etc

on unix there is the diff command which can be exec()'d & there are windows ports of diff (google) available
also google for the diff man page which shows you all the options


exec( 'diff -y file2 file2 ' , $yaks) ;
echo '<pre>';
print_r( $yaks ) ;

of course you may have reasons for wanting to roll your own , if not try the above.

12-10-2003, 06:46 AM
actually i would love to use something like that, but unfortunately it's not going to work in the context of this project.. ultimately i'm writing a script that needs to work on any server w/ apache and php, so relying on programs that may or may not be installed isn't going to be acceptable.. guess i'll just keep hacking away at it, i think i'm making some progress. if i can get it done in a small function i'll post it here.