我想从txt文件中删除副本。现在,我使用它来删除重复项:
$lines = file('input.txt');
$lines = array_unique($lines);
file_put_contents('output.txt', implode($lines));问题是,代码只对像beef bbq recipe和beef bbq recipe这样的情况删除重复。在我的例子中,如果txt文件包含关键字,如:
beef bbq recipe
beef easy recipe
beef steak recipe
bbq recipe beef
beef bbq recipe
recipe bbq beef将带着以下结果返回:
beef bbq recipe
beef easy recipe
beef steak recipe
bbq recipe beef
recipe bbq beef相反,我希望结果看起来如下:
beef bbq recipe
beef easy recipe
beef steak recipe因此,我希望像beef bbq recipe、bbq recipe beef和recipe bbq beef这样的案例也被视为重复案例。有什么解决办法吗?谢谢
发布于 2022-04-02 14:26:08
在删除重复项之前,可以使用array_map、explode和sort将所有行的关键字按相同的顺序排列:
$lines = file('input.txt');
// sort keywords in each line
$lines = array_map(function($line) {
$keywords = explode(" ", trim($line));
sort($keywords);
return implode(" ", $keywords);
}, $lines);
$lines = array_unique($lines);
file_put_contents('output.txt', implode("\n", $lines));这将迭代数组,并按字母顺序排列每一行的关键字。之后,您可以使用array_unique删除重复的行。
https://stackoverflow.com/questions/71718260
复制相似问题