0

I am using below php code to process two textareas called namelist and placelist and echo it to 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;
}

?>

But above code processing the blank lines in my textareas ? I need to avoid blank lines from echoing. for example, if the namelist contains

Tom
George

and placelist contains

GK
US

I will get output like:

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

But If there is a blank line in an of the textarea it processing the blank line too. eg:

Tom
George

and

GK

US

It will give below output like

My name is Tom and I am from GK 
My name is George and I am from
acr
  • 1,674
  • 11
  • 45
  • 77

2 Answers2

2

Try this:

Using regex to eliminate blank lines before exploding (works well for any number of consecutive blank lines)

$name = preg_replace('/\n+/', "\n", trim($_POST['namelist']));
$place = preg_replace('/\n+/', "\n", trim($_POST['placelist']));
Ajith S
  • 2,907
  • 1
  • 18
  • 30
0

You can remove the blank line from the array by the following code

$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;
}
}

Then you can use the two new array i.e $new_names and $new_places

Ryan decosta
  • 455
  • 1
  • 4
  • 10