简体   繁体   中英

Parsing text file in PHP

I need to parse text file in PHP. Pleas see below, I have uploaded it as an image. I need to get the fields market in yellow.

Tried many ways, but not confidence of any. Could somebody help me?

Thanks

在此输入图像描述

You can process the file with regular expression and some tokenizing. it appears that your field seperater value is '/' and record separator is '\\r\\n\\r\\n'.

$string = "data"; //lets assume your data is contained in one string
$records = preg_split("/^[\r\n\s]+$/", $string); 
//this line assume your file contains dos formatting, change to "/\r\r/" for osx and "/\n\n/" for unix

$data = array();
foreach ($records as $record) { 
     $fields = explode("/", $records);
     $data[] = array($fields[2], $fields[3], $fields[7], $fields[16);
}

var_dump($data);

Please note that the record separator is important and you will need to adjust it based on the file encoding.

Update. i have improved the record separator to be an empty line rather than two consecutive new lines.

Try the following:

$pattern[] = '#[\d]{02}-[\d]{2}-[\d]{2}/[\d]{2}\s[A-Z]{1}\s[\d]{2}#';
$pattern[] = '#EVENT=[A-Z]{3,}#';
$pattern[] = '#AFLR=[\d]{3}-[\d]{3}#';
$res = array();
foreach ($pattern as $key => $value){
    if (preg_match_all($value, $text, $matches)){
        $res[] = $matches[0];
    } else {
        $res[] = NULL;
    }
}

It looks like EVENT and AFLR are variable names that will remain constant, so I hardcoded those letters. If that's not the case, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM