2010-09-01 72 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