Регулярное выражение для USDA

O
На сайте с 29.05.2008
Offline
195
460

Здравствуйте.

ASCII files are delimited. All fields are separated by carets (^) and text fields are
surrounded by tildes (~). A double caret (^^) or two carets and two tildes (~~) appear
when a field is null or blank. Format descriptions include the name of each field, its type
[N = numeric with width and number of decimals (w.d) or A = alphanumeric], and
maximum record length. The actual length in the data files may be less and most likely
will change in later releases. Values will be padded with trailing zeroes when imported
into various software packages, depending on the formats used.

Пример строки (в конце строки ^ отсутствует):

~01001~^~0100~^~Butter, salted~^~BUTTER,WITH SALT~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87

Как лучше отловить значения в PHP?

iqmaker
На сайте с 17.04.2012
Offline
309
#1

Если верить этому: https://github.com/ffxfiend/usda-import/blob/master/usda_import.py

то на python это будет так выглядеть:


def parseLine(line):
line = line.rstrip('\n\r')
line = line.replace('~', '')
line = line.split('^')
return tuple(line)

print parseLine('~01001~^~0100~^~Butter, salted~^~BUTTER,WITH SALT~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87')

переводя в php, получим нечто вроде:


<?php
function parseLine($line){
$line = trim($line);
$line = str_replace( "~", "", $line);
$line = split("\^", $line);
return $line;
}

print_r( parseLine('~01001~^~0100~^~Butter, salted~^~BUTTER,WITH SALT~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87') );
?>
J
На сайте с 20.02.2014
Offline
120
jkm
#2

http://php.net/manual/en/function.str-getcsv.php


$text = '~01001~^~0100~^~Butter, salted~^~BUTTER,WITH SALT~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87';
var_dump(str_getcsv($text, '^', '~'));
O
На сайте с 29.05.2008
Offline
195
#3

jkm, написал через explode(). str_getcsv() в PHP 5.5 deprecated, но fgetcsv() то, что искал.

Авторизуйтесь или зарегистрируйтесь, чтобы оставить комментарий