Reputation: 19
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
Upvotes: 0
Views: 178
Reputation: 7795
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.
Upvotes: 0
Reputation: 13535
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.
Upvotes: 2