Reputation:
I'm trying to figure out how to convert html textarea into php array,
I've used a form with POST to deliver the query to the php script, and the php file is getting them with the following line:
$ids = array($_POST['ids']);
Needless to say that it puts everything into one line
Array ( [0] => line1 line2 line3 line4 )
I need the final results to replace this:
$numbers = array(
"line1",
"line2",
"line3",
"line4"
);
What would be the best approach to divide and re-parse it ?
Upvotes: 25
Views: 42308
Reputation: 14173
Using an explode on \n
is a proper way to get new lines. keep in mind though that on some platforms the end of line is actually send by \r\n
, so just exploding on \n
could leave you with extra data on the end of each line.
My suggestion would be to remove the \r
before exploding, so you dont have to loop through the entire array to trim the result. As a last improvement, you dont know that there actually is a $_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));
?>
Upvotes: 58
Reputation: 1688
Use this
$new_array = array_values(array_filter(explode(PHP_EOL, $input)));
explode
-> convert textarea to php array (that lines split by new line)
array_filter
-> remove empty lines from array
array_values
-> reset keys of array
Upvotes: 4
Reputation: 270
I would've done the explode by Hugo like this:
$ids = explode(PHP_EOL, $input);
manual Predefined Constants
Just my two cents...
Upvotes: 14
Reputation: 1967
Try with explode function:
$ids = $_POST['ids']; // not array($_POST['ids'])
$ids = explode(" ", $ids);
The first parameter is the delimiter
which could be space, new line character \r\n
, comma, colon etc. according to your string from the textarea (it's not clear from the question whether values are separated by spaces or by new lines).
Upvotes: -1
Reputation: 6573
If the textarea simply has line breaks per entry then I'd do something like:
$ids = nl2br($_POST['ids');
$ids = explode('<br />',$ids); //or just '<br>' depending on what nl2br uses.
Upvotes: -1