2009-09-09 33 views
1

我在html中有一个带有文本区域的窗体。 我想在php中获取这个文本区域的内容,以便每行可以存储在一个数组中。我试着用'/ n'来使用implode。但它不起作用。我怎样才能做到这一点。将文本区域的内容转换为数组

这里是我的代码

$notes = explode('/n',$_POST['notes']); 

回答

9

您需要使用这样的:

$notes = explode("\n", $_POST['notes']); 

(反斜杠,而不是正斜杠,以及双引号代替单引号)

7

Palantir的解决方案只有当行以\ n结尾(Linux默认行结束)时才会起作用。

例如,

$text  = "A\r\nB\r\nC\nD\rE\r\nF";  
$splitted = explode("\n", $text); 

var_dump($splitted); 

将输出:

array(5) { 
    [0]=> 
    string(2) "A " 
    [1]=> 
    string(2) "B " 
    [2]=> 
    string(1) "C" 
    [3]=> 
    string(4) "D E " 
    [4]=> 
    string(1) "F" 
} 

如果没有,你应该这样做:

$text  = "A\r\nB\r\nC\nD\rE\r\nF"; 
$splitted = preg_split('/\r\n|\r|\n/', $text); 
var_dump($splitted); 

或者这样:

$text  = "A\r\nB\r\nC\nD\rE\r\nF"; 
$text  = str_replace("\r", "\n", str_replace("\r\n", "\n", $text)); 
$splitted = explode("\n", $text); 
var_dump($splitted); 

我想最后一个会更快因为它不使用正则表达式。

例如,

$notes = str_replace(
    "\r", 
    "\n", 
    str_replace("\r\n", "\n", $_POST[ 'notes' ]) 
); 

$notes = explode("\n", $notes); 
0

不要使用PHP_EOL表单的textarea的数组,使用它:

array_values(array_filter(explode("\n", str_replace("\r", '', $_POST['data']))))