PHP结果数据溢出/爆炸,带有赋值

时间:2017-02-24 15:50:49

标签: php

我是PHP的新手并且正在努力获得一些结果,但未能实现我的目标。我有包含这样的数据的文本文件,

APAC|AU|enable|SYD1925|8|20150929|WORKING
APAC|AU|disable|ADL7235|3|20120123|RESIGNED
APAC|NZ|disable|NZ1356|6|20110123|RESIGNED
APAC|NZ|enable|NZ1356|3|20130123|WORKING

我正在尝试搜索“AU”&&这个文本“启用”,逐行,我有点成功。这是我的代码示例;

public function scan1()
{
    $file = FCPATH.'uploads/example.txt';
    // the following line prevents the browser from parsing this as HTML.
    header('Content-Type: text/plain');
    $search1 = "AU"; 
    $search2 = "enable";
    $lines = file($file); 
    foreach($lines as $line) 
    { 
        if(stristr($line,$search1) && stristr($line,$search2))
            echo $line;
    } 
}

现在,我正在尝试爆炸/拆分输出数据并分配变量/数组以保存在数据库中,但我没有这样做,有人可以帮助或给我一些方向来实现这一点。谢谢

3 个答案:

答案 0 :(得分:0)

首先,使用file_get_contents获取文件内容:

$str = file_get_contents(FCPATH.'uploads/example.txt');

然后,使用正则表达式(preg_match_all)查找您要查找的所有文本部分:

preg_match_all("/APAC\\|(\w{2}\\|\w+)/", $str, $matches);

然后调整数组,使'AU'和'enabled'分开(array_mapexplode):

$matches = array_map(function ($v) { return explode('|', $v); }, $matches[1]);

所以,print_r($matches);返回:

Array
(
    [0] => Array
        (
            [0] => AU
            [1] => enable
        )

    [1] => Array
        (
            [0] => AU
            [1] => disable
        )

    [2] => Array
        (
            [0] => NZ
            [1] => disable
        )

    [3] => Array
        (
            [0] => NZ
            [1] => enable
        )

)

最后,foreach循环:

foreach($matches as $k => $kv)
{
    $search1 = $kv[0]; // AU
    $search2 = $kv[1]; // enabled
}

答案 1 :(得分:0)

Please show us your_table scheme. If '$db' is a handle of the db connection :

foreach($lines as $line) 
{ 
    if(stristr($line,$search1) && stristr($line,$search2))
    {
        $arr = explode("|", $line);
        $query = "INSERT INTO your_table VALUES ('".$arr[0]."', '".$arr[1]."', '".$arr[2]."', '".$arr[3]."', '".$arr[4]."', '".$arr[5]."')";
        $db->query($query);
    }
} 

答案 2 :(得分:0)

这可以按预期工作:

public function scan1()
{
    $file = FCPATH.'uploads/example.txt';
    // the following line prevents the browser from parsing this as HTML.
    header('Content-Type: text/plain');
    $search1 = "AU"; 
    $search2 = "enable";
    $lines = file($file); 
    foreach($lines as $line) 
    { 
        if(strpos($line,$search1) !== false && strpos($line,$search2) !== false)
            echo $line;
    } 
}

使用strpos功能进行检测。

相关问题