我想逐行读取文件,并在unıx上搜索php脚本的每行另一个文件。将结果写入另一个文件。
我该怎么做?我的意思是,
file1:
192.168.1.2
192.168.1.3
192.168.1.5
file2:
.....
192.168.1.3
192.168.12.123
192.168.34.56
192.168.1.5
....
file3:
192.168.1.3
192.168.1.5
我想读取每一行file1并搜索每一行file2。如果我有匹配,写入结果file3.
<?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);
在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
)