【问题标题】:Read a text file line by line and search eachline another file php script逐行读取文本文件并搜索每一行另一个文件 php 脚本
【发布时间】:2025-12-16 02:15:02
【问题描述】:

我想逐行读取一个文件,并在 unıx 上使用 php 脚本逐行搜索另一个文件。将结果写入另一个文件。

我该怎么做? 我的意思是;

文件1:

192.168.1.2
192.168.1.3
192.168.1.5

文件2:

.....
192.168.1.3
192.168.12.123
192.168.34.56
192.168.1.5
....

文件3:

192.168.1.3
192.168.1.5

我想每行读取file1并搜索每行file2。如果我有匹配这个搜索写入结果file3。

【问题讨论】:

  • 对此很抱歉,但我不是开发者..所以我对问题进行了很多研究,但我发现了很多问题,但我发现这不仅仅是我的问题之一,只是其中的一部分,所以我必须是快点...

标签: php linux bash shell unix


【解决方案1】:
<?php
$file1 = file('file1', FILE_SKIP_EMPTY_LINES);
$file2 = file('file2', FILE_SKIP_EMPTY_LINES);
$file3Content = implode('', array_intersect($file1, $file2));
file_put_contents('file3', $file3Content);

【讨论】:

  • 感谢您的回答!我不得不问一些关于它的案例。 file1 " 192.168.1.2 192.168.1.3 192.168.1.5 " 和 file2 "..... 2192.168.1.3' '192.168.12.123' cre1 '192.168.34.56'corewe2 '192.168.1.5' core ...." 在这种情况下如何将 file1 行搜索到 file2?
【解决方案2】:

在 PHP 中,您可以使用 file() 函数读取这两个文件,它们都将作为数组返回。然后使用array_intersect()。考虑这个例子:

$ip1 = file('ip1.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$ip2 = file('ip2.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$results = array_intersect($ip1, $ip2); // intersection of two arrays
$ip3 = implode("\n", $results); // put them back together
file_put_contents('ip3.txt', $ip3); // put it inside the third file

$results 应该包含(根据您的示例):

Array
(
    [1] => 192.168.1.3
    [2] => 192.168.1.5
)

【讨论】: