Reputation: 117
I have text file like below(note the whitespaces at the start):
aaaaaaaaaa
abbbbbbbbbbb bbbbbbbbbb
ccccccccccccc ccccccccccc cccccccccc
ddddddddddd ddd dddddd ddddd
eeeeeeeeeee
How can I remove all whitespaces from beginning of each line?
Expected output:
aaaaaaaaaa
abbbbbbbbbbb bbbbbbbbbb
ccccccccccccc ccccccccccc cccccccccc
ddddddddddd ddd dddddd ddddd
eeeeeeeeeee
I tried to use ltrim()
, but it doesn't seem to work:
$liness = file('file.txt');
$lines = ltrim($liness);
file_put_contents('file.txt', implode($lines));
echo $lines;
Upvotes: 1
Views: 1688
Reputation: 166
You need to read file line by line to trim.
<?php
$file = fopen('yourfile', "r");
$new_file="";
if($file){
while (($line = fgets($file)) !== false) { // read file one line at a time.
$newfile .= ltrim($line); // trim it! trim it! :)
}
fclose($file);
echo $newfile; // !Adios
} else die('Unable to redy the file. :(');
Here is a fiddle for you
Other way to read the file in dom and use Reg-ex to fine " .." find multiple space and replace with only one.
Upvotes: 0
Reputation: 1612
Read file into array, trim each arrays element and put together into a string, put that string back into file:
$lines = file('file.txt')
$lines = array_map('ltrim', $lines);
$str = implode($lines);
file_put_contents('file.txt',$str);
//echo nl2br($str) - to see your new file string
//print_r($lines) - to see file lines as array
Use PHPs trim functions.
trim(' a d d d ');
//result: 'a d d d', beginning and ending whitespaces removed
There is also ltrim()
, and rtrim()
functions to remove left and right spaces only.
Upvotes: 1
Reputation: 11689
Ok to ltrim()
, but use it with array_map()
:
$lines = array_map( 'ltrim', $liness );
file_put_contents( 'file.txt', implode($lines) );
And, don't use echo
for an array, use print_r()
instead. Or:
foreach( $lines as $line ) echo "$line\n";
Upvotes: 3