【问题标题】:avoid blank lines in a textarea using php [duplicate]使用php避免文本区域中的空行[重复]
【发布时间】:2013-10-17 05:18:06
【问题描述】:

我正在使用下面的 php 代码来处理两个名为 namelistplacelist 的文本区域并将其回显到 html。

<?php

$namelist = $_POST['namelist'];
$placelist = $_POST['placelist'];

$names = explode("\n", $namelist); 
$places = explode("\n", $placelist); 

$entries = min(count($names), count($places));

for ($i = 0; $i < $entries; $i++) {
$name  = trim($names[$i]); 
$place = trim($places[$i]);
echo "My name is $name and I am from $place ".PHP_EOL;
}

?>

但上面的代码处理我的 textareas 中的空白行?我需要避免空行回显。 例如,如果namelist 包含

Tom
George

placelist 包含

GK
US

我会得到如下输出:

My name is Tom and I am from GK 
My name is George and I am from US

但是如果文本区域中有一个空行,它也会处理空行。例如:

Tom
George

GK

US

它会给出如下输出

My name is Tom and I am from GK 
My name is George and I am from

【问题讨论】:

标签: php html textarea


【解决方案1】:

试试这个:

使用regex 在爆炸前消除空行(适用于任意数量的连续空行)

$name = preg_replace('/\n+/', "\n", trim($_POST['namelist']));
$place = preg_replace('/\n+/', "\n", trim($_POST['placelist']));

【讨论】:

    【解决方案2】:

    您可以通过以下代码从数组中删除空行

    $names = explode("\n", $namelist); 
    $places = explode("\n", $placelist); 
    
    foreach($names as $name)
    {
    $name=trim($name);
    if($name!="")
    {
    $new_names[]=$name;
    }
    }
    
    foreach($places as $place)
    {
    $place=trim($place);
    if($place!="")
    {
    $new_places[]=$place;
    }
    }
    

    然后你可以使用两个新数组,即 $new_names 和 $new_places

    【讨论】:

    • 如果我插入 \r 而不是 \n 会怎样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2012-09-02
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    相关资源
    最近更新 更多