vendredi 8 mai 2015

Read external file match specific string in first column and return respective string of second column in php

I have two text files, csvurl.txt and tickerMaster.txt
tickerMaster.txt
H0001

Remarks: No ""H0002"" in tickerMaster.txt

csvurl.txt
H0001, URL1
H0002, URL2

I would like to read the entries in tickerMaster.txt one by one, say H0001, H0002...
and createURL by matching the data in csvurl.txt. So I am using following code...

<?php
  function createURL($ticker){
    $file = 'csvurl.txt';
    header('Content-Type: text/plain');
    $contents = file_get_contents($file);
    $sep = ',';
    $pattern = preg_quote($searchfor, '/');
    $searchfor = $ticker;
    $pattern = "/^($searchfor\w+)$sep.*$/m";
    if (preg_match_all($pattern, $contents, $matches)){
    echo implode($matches[0])."\n";
    }
    else{
        echo "No matches found";
    }
}

function main(){
$mainTickerFile = fopen("tickerMaster.txt", "r");
while(!feof($mainTickerFile)){
    $companyTicker = fgets($mainTickerFile);
    $companyTicker = trim($companyTicker);
    $fileURL = createURL($companyTicker);
    }
}
main()
?>

However, what I got is the whole line on the information in csvurl.txt for example:
No matches found H0001, URL1 H0002, URL2

My desired output is just:
URL1

Actually, I am looking for the function like vlookup in excel, but I cant search any solution for this kind of matching. Thanks.

Aucun commentaire:

Enregistrer un commentaire