Parse a textarea form separated by a comma or a new line

I have textarea in a form that allows users to enter a list of numbers separated by a newline or comma. I need the numbers entered to be entered into an array. Unfortunately, the code I have does not work all the time. If users enter data with a comma and a new line, then the comma remains in the resulting array. In addition, if they add a new line at the end of the text field, then it enters an empty value into the array. The code I have is below:

$data = preg_split( "[\r\n]", $_POST[ 'textarea' ] );
if (count($data) == 1) {
    $string = $data[0];
    $data = explode(',', $string);
}

I was hoping for some help on how to get around the problems that I am having.

+5
source share
6 answers

" , "
, , , ? " " ?

<?php
$input = '1,2,3
4,5,,,,
,6,
7
,8,9';

$data = preg_split("/[\r\n,]+/", $input, -1, PREG_SPLIT_NO_EMPTY);
var_dump($data);

array(9) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
  [4]=>
  string(1) "5"
  [5]=>
  string(1) "6"
  [6]=>
  string(1) "7"
  [7]=>
  string(1) "8"
  [8]=>
  string(1) "9"
}
+11
$input = '1,2,3
4,5,,,,
,6,
7
,8,9
';

$data = str_replace(array("\r", "\n"), ',', $input);
$data = array_filter(explode(',', $data));

var_dump(array_values($data));

array(9) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
  [4]=>
  string(1) "5"
  [5]=>
  string(1) "6"
  [6]=>
  string(1) "7"
  [7]=>
  string(1) "8"
  [8]=>
  string(1) "9"
}
+3

, +, , :

$data = preg_split( "[\r\n]", $_POST[ 'textarea' ] );

Try:

$data = preg_split("/[\r\n]+/", $_POST[ 'textarea' ]);
0

"" :

$data = preg_split("[\r\n"], trim($_POST["textarea"]));

. - csv - :

trim($data, ",");

. http://php.net/trim

0
source
$data = preg_split( "/[\r\n]+|,/", trim($_POST['textarea']) );

This will be separated by either newlines or commas, and will eliminate any trailing newlines.

0
source

If you want to divide also multi-zone spaces into separate spaces, trim the spaces before and after and also allow the semicolon ';' instead of just a comma ',', then this code worked for me. I am sure this can be done in one preg_split and / or preg_replace, though!

$string = '  1,2,3
   4,5,;,,
   ;6,
7
,   8   ,9; 10  ; 11;';

$tmp = preg_split("/[\r\n,;]+/", $string, -1, PREG_SPLIT_NO_EMPTY);
foreach($tmp as $val)
{
    $val = trim(preg_replace('!\s+!', ' ', $val));
    if($val != "")
        $data[] = $val;
}

var_dump($data);
/* Returns
array(11) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
  [4]=>
  string(1) "5"
  [5]=>
  string(1) "6"
  [6]=>
  string(1) "7"
  [7]=>
  string(1) "8"
  [8]=>
  string(1) "9"
  [9]=>
  string(2) "10"
  [10]=>
  string(2) "11"
}
*/
0
source

All Articles