Vishnu Fauzdar
Vishnu Fauzdar

Reputation: 60

How to search string from one file to another file in php?

I have One .txt file with millions of records. Now I have another file with 20 records and now i will want to search second file matches records from first file. I am using below code for find records using php:

$million_records    = file('file/snp-db.txt');
$search_word         = file('file/test.txt');
foreach($searchword as $word){  
    foreach($million_records as $single_record){     
     if(strpos($single_record, $word) !== false){
        echo $single_record .'<br>';   
       }   
    }
}

but this code is returned only last value like this: test.txt file have only 4 records

rs12564807
rs3131972   
rs148828841
rs12124819

now i want to find these records from snp-db.txt file that have million of records in this format:

rs12564807  1   734462  AA
rs3131972   1   752721  GG
rs148828841 1   760998  CC
rs12124819  1   776546  AG
rs115093905 1   787173  GG
rs11240777  1   798959  AG
rs7538305   1   824398  AC
rs4970383   1   838555  CC
rs4475691   1   846808  CC
rs7537756   1   854250  AA
rs13302982  1   861808  GG
rs55678698  1   864490  CC
i6019299    1   871267  CC

now i received only rs12124819 result. can you help me whats going wrong with this code

Upvotes: 1

Views: 92

Answers (1)

Kostis
Kostis

Reputation: 1105

The problem lies with the fact that each $word and $single_record carry a hidden new line with them that you need to remove before testing for occurrence of $single_record in $word.

Also it'll be much faster to iterate through the million_records file first (and only once)

$million_records = file('file/snp-db.txt');
$search_word = file('file/test.txt');

foreach ($million_records as $single_record) {
    $single_record = preg_replace("/\r|\n/", '', $single_record);
    foreach ($search_word as $word) {
        $word = preg_replace("/\r|\n/", '', $word);
        if (strpos($single_record, $word) !== false) {
            echo $single_record."\r\n";
        }
    }
}

Upvotes: 1

Related Questions