Bee
Bee

Reputation: 309

how to put two or more line from a text file to a variable using php?

one line in a variable is good but how assign in a variable multiple lines in text file?

--sample text file----

jeff              ->line0
35                ->line1
123456            ->line2
"this is          ->line3
the message       ->line4
from you"         ->line5

How to assign the line 3,4 and 5 to a single variable?

code:

<?php

    $lines = file('sample.txt');
    $vara= $lines[0];
    $varb= $lines[1];
    $varc= $lines[2];

   ?>

Upvotes: 0

Views: 35

Answers (3)

Amani Ben Azzouz
Amani Ben Azzouz

Reputation: 2565

you can do like this:

 //concatenate the last 3 lines and remove the break lines
 $result=preg_replace('/\s{2,}/', ' ', $lines[3].$lines[4].$lines[5]);
 print $result;

Output:

"this is the message from you"

Update:

Loop all lines in the file:

    $lines = file('sample.txt');
    $result="";
   if (array_key_exists(3,$lines)) {
    //assuming that always the comment begins from line 3
    for($i=3; $i<count($lines);$i++){
      $result .=preg_replace('/\s{2,}/', ' ', $lines[$i]);
    }
    }
    print $result;

Upvotes: 1

PHPhil
PHPhil

Reputation: 1540

You can just assign multiple lines to a single variable using a dot .

<?php

$lines = file('sample.txt');
$a= $lines[0];
$b= $lines[1];
$c= $lines[2];
$d= $lines[3] . $lines[4] . $lines[5];

echo $a . "<br>";
echo $b . "<br>";
echo $c . "<br>";
echo $d . "<br>";


?>

output:

jeff
35
123456
"this is the message from you" 

Upvotes: 1

Manwal
Manwal

Reputation: 23836

Your question is very hard to understand for me and having errors.

$var a= $lines[0];
^================> //using $ before var is wrong you should use following
var $a= $lines[0];

As i can understand you can do following:

<?php

    $lines = file('sample.txt');
    var $a= $lines[0];
        $a += $lines[1];
        $a += $lines[2];

?>

Upvotes: 0

Related Questions