Reputation: 309
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
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;
"this is the message from you"
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
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
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