如何拆分空格分隔文件?

时间:2010-06-15 07:29:56

标签: php regex

我想导入这个:

http://en.wikipedia.org/wiki/List_of_countries_by_continent_%28data_file%29

格式如下:

AS AF AFG 004 Afghanistan, Islamic Republic of
EU AX ALA 248 Åland Islands
EU AL ALB 008 Albania, Republic of
AF DZ DZA 012 Algeria, People's Democratic Republic of
OC AS ASM 016 American Samoa
EU AD AND 020 Andorra, Principality of
AF AO AGO 024 Angola, Republic of
NA AI AIA 660 Anguilla

如果我这样做

<? explode(" ",$data"); ?>

除了超过1个字的国家/地区之外,它的效果很好。

我怎么能把它拆分,所以我得到前4位数据(字符/整数)和第5位数据是剩下的?

这是在php

谢谢

4 个答案:

答案 0 :(得分:11)

explode函数采用可选的限制参数。将您的函数调用更改为:

<?php explode(" ", $data, 5); ?>

您将获得国家/地区名称作为数组中的最后一个元素,包含空格。

答案 1 :(得分:3)

使用unpack

$format = "A2cont/x/A2alpha2/x/A3alpha3/x/A3num/x/a*eng";
$line = "AS AF AFG 004 Afghanistan, Islamic Republic of";
$ar = unpack($format, $line);

它产生:

array (
  'cont' => 'AS',
  'alpha2' => 'AF',
  'alpha3' => 'AFG',
  'num' => '004',
  'eng' => 'Afghanistan, Islamic Republic of',
)

这样做的好处是可以生成一个关联数组(注意斜杠之前的文本),并在输入无效时发出警告。

答案 2 :(得分:0)

您可以使用preg_match,您的文字将在$match[5];

<?php
$str = 'AS AF AFG 004 Afghanistan, Islamic Republic of';
$chars = preg_match('/([A-Z]*)\ ([A-Z]*)\ ([A-Z]*)\ ([0-9]*)\ (.*)\ /', $str, $match);
print_r($match);
?>

答案 3 :(得分:0)

也许sscanf也可以做你需要的事情:

<?php
// in my example I loaded the data in an array line by line
$lines = file('sscanf_data.txt');

foreach($lines as $line) {
    $data = array();
    // define the format of the input string, assign the 
    // extracted data to an associative array
    sscanf($line, "%s %s %s %s %[^.]", 
        $data['col_1'], 
        $data['col_2'], 
        $data['col_3'], 
        $data['col_4'], 
        $data['col_5']);

    // dump array contents
    print_r($data);
}

输出:

Array
(
    [col_1] => AS
    [col_2] => AF
    [col_3] => AFG
    [col_4] => 004
    [col_5] => Afghanistan, Islamic Republic of

)
...

好处是,如果您将数据存储在关联数组中,那么您已经拥有了用于将数据插入数据库的字段值对。