如何使用 php 比较两个文件来找到多余的行?
我有两个文件。
第一个有 482 行。 第二个只有 519 行。
我想通过使用 php.ini 比较两个文件来找到额外的行。
假设我的第一个文件有这样的行
Mango
Orange
Cherry
Apple
Blackberry
,假设我的第二个文件看起来像这样
Apple
Orange
Mango
Banana
Cherry
Blackberry
请注意:这些行是随机顺序的。现在我想使用 php 脚本删除相同的行并保留多余的行。例如,文件 1 包含行 Mango
。文件 2 也包含该行,但顺序是随机的。所以我想删除该行。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
将每个文件加载到字符串数组中(例如,使用 file_get_contents)。
执行一些循环,对于数组 2 中的每个项目,确定该项目是否存在于数组 1 中。如果存在,则从数组 2 中删除该项目并继续。
完成后,数组 2 将仅包含唯一的行。
编辑:
如果您只想删除 File2 中同时存在于 File1 中的行,则您需要查找唯一值(其中顺序并不重要)。一种快速的方法是使用 array_diff 函数。
这是一个示例:
如果您喜欢使用我在第一部分中提到的循环手动执行此操作,则可以按以下方式执行此操作:
Load each file into a string array (using file_get_contents, for example).
Perform some loops that, for every item in array 2, determine if the item exists in array 1. If so, remove the item from array 2 and continue.
When complete, array 2 will contain only unique lines.
Edit:
If you just want to remove lines in File2 that are also present in File1, you're looking for the unique values (where order does not matter). A quick way to do this is using the array_diff function.
Here is an example:
If you prefer to do this manually using loops like I mentioned in the first part, here is how you would do it:
我采取了 JYelton 建议的相同方法。
此处演示:http://codepad.org/lCa68G76
I took the same approach JYelton has suggested.
Demo here: http://codepad.org/lCa68G76
通过将每个文件的行读入一个列表来创建两个列表,然后比较它们。遍历 list1 并删除 list2 中未找到的所有项目,反之亦然。
Make two lists by reading in the lines of each file into one list, and then compare them. Go through list1 and remove every item that isn't found in list2, or vice versa.
有很多片段可以做到这一点:
http://web.archive.org/web/20080506155528/http://software.zuavra.net/inline-diff/
https://github.com/paulgb/simplediff/blob/5bfe1d2a8f967c7901ace50f04ac2d9308ed3169/simplediff.php(仅限数组)
http://www.holomind.de/phpnet/diff.src.php
There's a lot of snippets to do that:
http://web.archive.org/web/20080506155528/http://software.zuavra.net/inline-diff/
https://github.com/paulgb/simplediff/blob/5bfe1d2a8f967c7901ace50f04ac2d9308ed3169/simplediff.php (Arrays only)
http://www.holomind.de/phpnet/diff.src.php
检查两个数组是否包含值。
Check if both arrays contain values.
这需要用 PHP 脚本来完成吗?您可以在 bash 中轻松实现此目的:
Does this need to be done with a PHP script? You can achieve this in bash quite easily: