2010-06-15 51 views
3

我試圖導入此:如何拆分空格分隔的文件?

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位數據(字符/整數)和第五位數據是什麼仍然是?

這是在PHP

謝謝

+0

每個國家的名字後都有逗號嗎? – nik 2010-06-15 07:51:45

回答

11

explode函數有一個可選的限制參數。你的函數調用更改爲:

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

,你會得到國家的名稱作爲數組中的最後一個元素,包含空格。

+0

你打敗了我四秒......我認爲你應該得到最佳答案,而不是我。 – hbw 2010-06-15 07:41:22

+1

+1,但不要使用短打開的標籤 – 2010-06-15 07:45:06

+0

如果國家是捷克共和國,這將無法正常工作 – nik 2010-06-15 07:49:30

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); 
?> 
+2

沒有必要逃離這個空間。 – Gumbo 2010-06-15 07:40:47

+0

同樣在這個模式中,除空格以外的所有東西都是可選的(它只與5個空格相匹配的字符串)。在這種情況下,這可能不是問題,但儘可能具體可幫助避免意外的結果。 – 2010-06-15 07:56:05

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', 
) 

這具有產生一個關聯數組(注意斜線之前的文本),並且如果輸入的警告的優點是無效的。

+0

+1顯示我使用解壓函數:) – Max 2010-06-15 07:50:00

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 

) 
... 

的好處是,如果你存儲在一個關聯數組中的數據,你已經有場 - 值對用於將它們插入數據庫。