用逗号或换行符解析表格textarea [英] Parse form textarea by comma or new line

查看:117
本文介绍了用逗号或换行符解析表格textarea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本区域,该区域允许用户输入用换行符或逗号分隔的数字列表.我需要将他们输入的数字输入到数组中.不幸的是,我拥有的代码并非始终有效.如果用户输入逗号分隔的数据和换行符,则逗号将保留在结果数组中.另外,如果他们在文本字段的末尾添加换行符,则它将在数组中输入一个空值.我的代码如下:

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.

推荐答案

用换行符或逗号分隔的数字列表"
因此,您不在乎它是哪一个,或者是否有逗号换行符?那么,为什么不简单地将所有三个字符均用作分隔符并允许一个或多个"呢?

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

打印

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"
}

这篇关于用逗号或换行符解析表格textarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆