使用php避免textarea中的空白行

时间:2013-10-17 05:18:07

标签: php html textarea

我使用下面的PHP代码处理两个名为namelistplacelist的textareas并将其回显为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

但是如果textarea中有一个空行,它也会处理空白行。例如:

Tom
George

GK

US

它将提供以下输出,如

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

2 个答案:

答案 0 :(得分:2)

试试这个:

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

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

答案 1 :(得分:0)

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

$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