5

我正在尝试为我当地的志愿消防队编写地址警报脚本,但我被困住了。

我有一个名为 preplan.txt 的 txt 分隔文件,其中包含如下行:

Line1: REF00001 | NAME1 | ALERTADDRESS1 | LINK2DOWNLOADPDFINFOONADDRESS1 | NOTESONADDRESS1

Line2: REF00002 | NAME2 | ALERTADDRESS2 | LINK2DOWNLOADPDFINFOONADDRESS2 | NOTESONADDRESS2

Line3: REF00003 | NAME3 | ALERTADDRESS3 | LINK2DOWNLOADPDFINFOONADDRESS3 | NOTESONADDRESS3

等等。

我还有一个名为 $jobadd 的字符串,它是工作的地址......

我需要在php中做的是如果job地址与txt文件中的任何Alert Addresses相同($jobadd)然后显示相关的名称,地址,链接和注释..它还需要忽略它是否写是否大写。基本上如果 $jobadd = txt 文件中的地址显示该信息...

我似乎只能呼应最后一行。

4

3 回答 3

4

首先,将字符串拆分为行:

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

然后,也拆分和修剪这些线:

$data = array();

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

最后,$jobadd在#3 列中查找,即索引#2,如果找到则打印数据:

foreach($data as $item) {
    if(strtolower($item[2]) === strtolower($jobadd)) {
        // Found it!
        echo "Name: {$item[1]}, link: {$item[3]}, notes: {$item[4]}";
        break;
    }
}
于 2012-03-31T02:06:24.080 回答
1

更新

流线有点。只需输入正确的文件路径就$file可以了。

$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;
    }
}
于 2012-03-31T03:04:09.727 回答
0
<?php

    define('JOBADDR','ALERTADDRESS3');

    # get all lines
    $pl = file_get_contents('preplan.txt');
    $pl = explode("\n",$pl); 

    # cleanup
    foreach($pl as $k=>$p){ # goes through all the lines
        if(empty($p) || strpos($p,'|')===false || strtoupper($p)!==$p /* <- this checks if it is written in capital letters, adjust according to your needs */ )
            continue;

        $e = explode('|', $p); # those are the package elements (refid, task name, address, ... )
        if(empty($e) || empty($e[2])) # $e[2] = address, it's a 0-based array
            continue;

        if(JOBADDR !== trim($e[2])) # note we defined JOBADDR at the top
            continue;

        # "continue" skips the current line

        ?>


        <p>REF#<?=$e[0]; ?> </p>
        <p><b>Name: </b> <?=$e[1]; ?></p>
        <p><b>Location:</b> <a href="<?=$e[3]; ?>"><?=$e[2]; ?></a> </p>
        <p><b>Notes: </b> </p>
        <p style="text-indent:15px;"><?=empty($e[4]) ? '-' : nl2br($e[4]); ?></p>

        <hr />


        <?php
    }
于 2012-03-31T02:20:48.157 回答