Home > Back-end >  Is there an function that compares two text files in PHP?
Is there an function that compares two text files in PHP?

Time:12-23

I need a function to compare two text files and find the similarities between them. I have tried using "Strpos" and "similartext", but neither of them seem not to working. I am not sure how to compare the two files.

Here is my code which has two files text one that been track the keystrokes from the user and other is list of words that be compare to another file This code is designed to track the keystrokes of the user and compare them to a list of words. If the keystrokes match a word on the list, then the code will output the echo message otherwise nothing.



echo "<h3> <center>" . '#####Alert#####';
$text = "<br> Unsafe user Found";

$String = 'file.txt';
$list = 'wordlist.txt';





 //compare the difference between the string and the list of word 


    
for ($i = 0; $i <= 0; $i  ){
   
    if (strpos(file_get_contents ($String , $list) )!== false) {
            echo  $text;
            //mail($to, $subject, $message);
        }
      return false;


}

For example, if the user typed account it should echo message because the account word is on the list. However, if the user typed in a word that is not on the list, the program would not be able to echo a message.

Please accept my apologies for any errors

CodePudding user response:

To compare the contents of two txt files and find the similarities between them,Read the contents of both files into separate variables using the file_get_contents() function. Split the contents of each file into arrays of words using the explode() function. compare the words using the in_array() function. If a word from one array is found in the other array, you can output the string or take any other desired action.

echo "<h3> <center>" . '#####Alert#####';
$text = "<br> Unsafe user Found";

$String = 'file.txt';
$list = 'wordlist.txt';

// Read the contents of both files into separate variables
$stringContents = file_get_contents($String);
$listContents = file_get_contents($list);

// Split the contents of each file into arrays of words
$stringWords = explode(' ', $stringContents);
$listWords = explode(' ', $listContents);

// compare the words using `in_array() function`
foreach ($stringWords as $word) {
    if (in_array($word, $listWords)) {
        echo $text;
    }
}
  • Related