2010-09-01 41 views
2

我有一個<textfield>$_POST['list'])。PHP閱讀每行

如何獲取每行數值到數組鍵?

實施例:

<textfield name="list">Burnett River: named by James Burnett, explorer 
Campaspe River: named for Campaspe, a mistress of Alexander the Great 
Cooper Creek: named for Charles Cooper, Chief Justice of South Australia 1856-1861 
Daintree River: named for Richard Daintree, geologist 
</textfield> 

應轉換爲:

Array(
[Burnett River: named by James Burnett, explorer] 
[Campaspe River: named for Campaspe, a mistress of Alexander the Great] 
[Cooper Creek: named for Charles Cooper, Chief Justice of South Australia 1856-1861] 
[Daintree River: named for Richard Daintree, geologist] 
) 

感謝。

回答

5

使用explode功能,然後修剪結果陣列(擺脫任何剩餘\n\r或任何意外空格/製表符):

$lines = explode("\n", $_POST['list']); 
$lines = array_map('trim', $lines); 
+0

用於'array_map' /'trim'的+1 – 2010-09-01 16:18:46

2

您可以使用explode()並使用換行符\n進行爆炸。

$array = explode("\n", $_POST['list']); 
+0

爲了誰downvoted我們,請用註釋詳細說明。謝謝!鑑於蒂姆的回答,我會認爲是他。簡單說一下,上面的「大部分」都是有效的。有幾種情況,你詳細說明,它不起作用。這是否值得讚揚,即使它確實解決了答案,至少在**大部分時間裏都是如此? – 2010-09-01 15:36:26

+0

大部分時間裏_will_是回車。 – Tim 2010-09-01 15:45:35

+0

對,我明白這一點。但是,即使回車,上述仍然有效。並且回車將**很少**影響應用程序,除了是一個剩餘的字符。問題是,這確實解決了問題,即使它不是「最好的」路線。 – 2010-09-01 15:48:42

4

這是最安全方法來做到這一點。它不認爲你可以扔掉回車(\r)字符。

$list_string = $_POST['list']; 

// \n is used by Unix. Let's convert all the others to this format 

// \r\n is used by Windows 
$list_string = str_replace("\r\n", "\n", $list_string); 

// \r is used by Apple II family, Mac OS up to version 9 and OS-9 
$list_string = str_replace("\r", "\n", $list_string); 

// Now all carriage returns are gone and every newline is \n format 
// Explode the string on the \n character. 
$list = explode("\n", $list_string); 

Wikipedia: Newline