TextArea to array with PHP

I am trying to understand how to convert html textarea to php array,

I used the form with POST to deliver the request to the PHP script, and the php file receives them with the following line:

$ids = array($_POST['ids']); 

Needless to say, it puts everything on one line

 Array ( [0] => line1 line2 line3 line4 ) 

I need final results to replace this:

 $numbers = array( "line1", "line2", "line3", "line4" ); 

What would be the best approach to separation and reanalysis?

+7
source share
5 answers

Using an explosion on \n is the right way to get new lines. keep in mind that on some platforms the end of the line is actually sent \r\n , so just exploding at \n may leave you with extra data at the end of each line.

My suggestion was to remove \r before the explosion, so you don't have to iterate over the whole array to trim the result. As a final improvement, you do not know that there really is $_POST['ids'] , so always check it first.

 <? $input = isset($_POST['ids'])?$_POST['ids']:""; //I dont check for empty() incase your app allows a 0 as ID. if (strlen($input)==0) { echo 'no input'; exit; } $ids = explode("\n", str_replace("\r", "", $input)); ?> 
+24
source

I would make a Hugo explosion like this:

 $ids = explode(PHP_EOL, $input); 

manual Predefined Constants

Only my two cents ...

+4
source

If textarea just has line breaks for each entry, I would do something like:

 $ids = nl2br($_POST['ids'); $ids = explode('<br />',$ids); //or just '<br>' depending on what nl2br uses. 
0
source

Use this

  $ new_array = array_values โ€‹โ€‹(array_filter (explode (PHP_EOL, $ input)));

explode convert textarea to php array (strings separated by a new line)
array_filter remove empty rows from an array
array_values reset array keys

0
source

Try to explode the function :

 $ids = $_POST['ids']; // not array($_POST['ids']) $ids = explode(" ", $ids); 

The first parameter is delimiter , which can be a space, a new line character \r\n , a comma, a colon, etc. according to your line from the text box (it is not clear the question is whether the values โ€‹โ€‹are separated by spaces or new lines).

-one
source

All Articles