tags:

views:

221

answers:

2

I have a form with a text area in html. I want to get the content of this text area in php so that each line can be stored in an array. I tried using implode with'/n'. but its not working. how can i do that.

Here is my code

$notes = explode('/n',$_POST['notes']);
+5  A: 

You need to use this:

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

(Back slash, not forward slash, and double quotes instead of single quotes)

Palantir
+4  A: 

Palantir's solution will work only if the lines ends with \n (Linux default line ending).

Eg.

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

var_dump( $splitted );

will output:

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

If not, you should use this:

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

Or this:

$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 );

I think the last one will be faster because it does not use regular expressions.

Eg.

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

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