2014-06-12 54 views
0

我想逐行讀取一個文件並在每一行中搜索另一個文件,並使用php腳本在unıx.an上將結果寫入另一個文件。逐行讀取文本文件並在每行中搜索另一個文件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 

我想讀文件1各線和搜索每個行file2.And如果我有這樣的比賽搜索寫入結果文件3。

+1

[?你嘗試過什麼(http://mattgemmell.com/what-have-you-試過/) – kero

+0

@kingkero好帖子! – rpax

+0

對不起,但我不devaloper ..所以我挖了很多關於問題,但我不知道我的問題,只是其中的一部分,所以我必須快速瞭解它... – desscartes

回答

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); 
+0

感謝您的回答!我不得不問一些關於它的案例。文件1 「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' 核心 。 ...「在這種情況下,我怎樣才能將file1行搜索到file2? – desscartes

1

在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 
)