Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse form textarea by comma or new line

Tags:

php

I have a textarea in a form that allows users to enter a list of numbers separated by either a newline or a comma. I need the numbers they entered to be entered into an array. Unfortunately, the code I have does not work all the time. If users enter comma sepated data and a newline then the comma is left in the resulting array. In addition, if they add a newline at the end of the textfield 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 issues I am having.

like image 227
Adam L. Avatar asked Aug 14 '10 12:08

Adam L.


1 Answers

"a list of numbers separated by either a newline or a comma"
So, you do not care which one it is, or if there is a comma and a newline? Then why not simply use all three characters equally as separators and allow "one or more" of them?

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

prints

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"
}
like image 80
VolkerK Avatar answered Oct 18 '22 22:10

VolkerK