I have a textarea and a submit button and on click of the button I want that all the data seperated by a new line inserted into an array.
Here is the form file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<form action="export.php" method="POST">
<textarea name="num1" placeholder="Enter Numbers You Want To See records Of....">
</textarea>
<input type="submit" name="sub">
</form>
</body>
</html>
And Here is the PHP file
<?php
include 'connect.php';
$newnum = '';
$a = array($_POST['num1']);
foreach($a as $i=>$checknum) {
$newnum = "'".$checknum."'".',';
}
$newnum = rtrim($newnum,',');
echo "$newnum";
?>
This is what I am expecting: Input - 1111 222 333 444 55 Output - '1111','222','333','444','55'
CodePudding user response:
$a = "1111\n222\n333\n444\n55";
echo $a . PHP_EOL;
/*
1111
222
333
444
55
*/
// explode("\n", $a) ->
// Explodes input by new line into following array [1111, 222, 333, 444, 55]
// fn($line) => "'$line'" ->
// anonymous function that takes one input and wraps it between ''
// Replace with function($line) {return "'$line'";} if using PHP < 7.4
// array_map ->
// takes a callback function and an array and returns a new array by applying a callback to each item
// implode(',', ...) ->
// join all elements in new array with a separator ','
$newnum = implode(',', array_map(fn($line) => "'$line'", explode("\n", $a)));
echo $newnum;
/*
'1111','222','333','444','55'
*/
Actually you could just implode them with "','"
and add '
to both ends.
$newnum = "'" . implode("','", explode("\n", $a)) . "'";
CodePudding user response:
Try
$newnum = '';
$a = explode("\n", $_POST['num1']);
foreach($a as $i=>$checknum) {
$newnum. = "'".$checknum."'".',';
}
$newnum = rtrim($newnum,',');
CodePudding user response:
you can use :
$res = array_filter(array_map(function($value){
return trim($value);
}, explode("\n", $a)));
Even if the person add lot of spaces ou add lot of new lines, the code will work.
Regards
CodePudding user response:
assume input from textarea is:
7
10
55
$textbox_string = '7'.PHP_EOL.'10'.PHP_EOL.'55';
$arr = explode(PHP_EOL, $textbox_string);
$in_nums_query_str = implode(',', $arr);
$in_nums_query_str = str_replace(PHP_EOL, '', $in_nums_query_str);
$in_nums_query_str = str_replace(",", "','", $in_nums_query_str);
$in_nums_query_str = "'" . $in_nums_query_str . "'";
echo $in_nums_query_str;
will echo
'7','10','55'