我想计算PHP中上传文件中的重复单词,如何执行此任务?
假设我们正在处理文本文件,这是一个相对简单的任务:
// Get the contents of the file
$contents = file_get_contents('my_file.txt');
// Split the contents into an array of individual words
$words = explode(' ', $contents);
// Define arrays to track occurrences and duplicates
$occurrences = [];
$duplicates = [];
// Iterate through each word in the sample
foreach ($words as $word) {
// Increment the current occurrence count of current word
$occurrences[$word] = isset($occurrences[$word]) ? $occurrences[$word] + 1 : 1;
// If the word has occurred more than once, add it to our duplicates
if ($occurrences[$word] > 1) {
$duplicates[] = $word;
}
}
// Output the duplicates in a comma separated format
echo "Duplicates in file: " . join(", ", $duplicates);