acr
acr

Reputation: 1746

Echo from textarea using php

I want collect data from a text area and echo using php after removing the first line.I need to add few words along with the data

for example, below php is my php code which processing the text area id states

<?php

$text = $_POST['states'];
function getLines($text, $start, $end = false)
{
    $devices = explode("\n", $text);

    $output = "";
    foreach ($devices as $key => $line)
    {
        if ($key+1 < $start) continue;
        if ($end && $key+1 > $end) break;
        $output .= $line;
    }
    return $output;
}

echo getLines($_POST['devs'], 2);

?>

so If I enter enter below info in my text area

United State
Florida
Georgia
Illinois
New York
Texas

I will get output like

Florida
Georgia
Illinois
New York
Texas

I need output like below to suffix the first line from text area with other text

State Florida is in United State
State Georgia is in United State 
State Illinois is in United State
State New York is in United State
State Texas is in United State

As per the other answers, I have changed php to add the prefix work state

function getLines($text, $start, $end = false)
{
    $devices = explode("\n", $text);
    $prefix  = "State ";
    $suffix = echo " in $devices[0]";



    $output = "";
    foreach ($devices as $key => $line)
    {
        if ($key+1 < $start) continue;
        if ($end && $key+1 > $end) break;
        $output .= $prefix.$line.$suffix ;
    }
    return $output;
}

echo getLines($_POST['devs'], 2);


?>

But that doesnot working.I can able to add the prefix section alone like $output .= $prefix.$line; to get output like below

State Florida

how can I add the first line along with the echo to show output like

State Florida is in United States

Upvotes: 0

Views: 178

Answers (1)

DeiForm
DeiForm

Reputation: 664

Here it is. I had to modify it a little bit because with your pattern I was getting 1 more unneccessery line.

$text = "United State
Florida
Georgia
Illinois
New York
Texas
";

function getLines($text, $start, $end = false)
{
    $devices = explode("\n", $text);
    $prefix  = "State ";
    $suffix = " in ". $devices[0]."<br>";

    $output = "";
    $i = 0;
    foreach ($devices as $key => $line)
    {
        $i++;
        if ($key+1 < $start) continue;
        if ($i != count($devices)) {
        $output .= $prefix.$line.$suffix;
        }
    }
    return trim(preg_replace('/\s\s+/', ' ', $output));
}

echo getLines($text, 2);

Upvotes: 1

Related Questions