我使用下面的PHP代码处理两个名为namelist
和placelist
的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
答案 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