0

我正在使用下面的 php 代码来处理两个调用的文本区域namelist并将placelist其回显到 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
4

2 回答 2

2

尝试这个:

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

$name = preg_replace('/\n+/', "\n", trim($_POST['namelist']));
$place = preg_replace('/\n+/', "\n", trim($_POST['placelist']));
于 2013-10-17T06:54:49.677 回答
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

于 2013-10-17T05:28:01.617 回答