Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delimited txt file / strings issue

I am trying to do a address alert script for my local volunteer fire brigade and I'm stuck.

I have a txt delimited file called preplan.txt containing lines like this:

Line1: REF00001 | NAME1 | ALERTADDRESS1 | LINK2DOWNLOADPDFINFOONADDRESS1 | NOTESONADDRESS1

Line2: REF00002 | NAME2 | ALERTADDRESS2 | LINK2DOWNLOADPDFINFOONADDRESS2 | NOTESONADDRESS2

Line3: REF00003 | NAME3 | ALERTADDRESS3 | LINK2DOWNLOADPDFINFOONADDRESS3 | NOTESONADDRESS3

and so on.

I also have a string named $jobadd which is the address for a job...

What I need to do in php is if the job address is the same ($jobadd) as any of the Alert Addresses in the txt file then display relevant name, address, link and notes.. It needs to also ignore whether it is written in capital letters or not. Basically if $jobadd = a address in the txt file display that info...

I can only seem to echo the last line.

like image 846
AdamK Avatar asked Mar 31 '12 02:03

AdamK


2 Answers

First, split the string to lines:

$lines = explode("\n", $data); // You may want "\r\n" or "\r" depending on the data

Then, split and trim those lines, too:

$data = array();

foreach($lines as $line) {
    $data[] = array_map('trim', explode('|', $line));
}

Finally, look for $jobadd in column #3, i.e. index #2, and print the data if found:

foreach($data as $item) {
    if(strtolower($item[2]) === strtolower($jobadd)) {
        // Found it!
        echo "Name: {$item[1]}, link: {$item[3]}, notes: {$item[4]}";
        break;
    }
}
like image 154
Ry- Avatar answered Nov 20 '22 07:11

Ry-


Updated

Stream lined a bit. Just enter the correct file path for $file and you should be good to go.

$data = file_get_contents($file);

$lines = array_filter(explode("\n", str_replace("\r","\n", $data)));

foreach($lines as $line) {

    $linedata = array_map('trim', explode('|', $line));

    if(strtolower($linedata[2]) == strtolower($jobadd)) {
        // Found it!
        echo "Name: {$linedata[1]}, link: {$linedata[3]}, notes: {$linedata[4]}";
        break;
    }
}
like image 1
iambriansreed Avatar answered Nov 20 '22 08:11

iambriansreed