Is there way to replace last charcter in each line within file using php?
I have file that has bunch of lines and at the end of each line there is a character that I need to remove.
Do I have to read file line by line or is there magic that I can use to strip last character in each line of a file?
How would I do that?
Any help is appreciated.
You are going to have to read in each line and edit each line with. What OS are you using? Unix has some useful tools (awk, sed) for this type of problem.
Is the character the same character every time? You can load your file into a string using
$mystr = file_get_contents("myfile.txt");
and then use preg_replace to remove your character from the string.
$mystr = preg_replace("yourcharhere","",$mystr);
and then put your string back into the file
$fh = fopen("myfile.txt", 'w');
fwrite($fh, $stringData);
fclose($fh);
You can also add yourcharacterhere+newline in the preg_replace and then cahnge the "" to a newline. That will make it so it only removes your character before a newline. If you have different characters you need to remove, you can use a regular expression and a wildcard to remove any character before a newline.
You would either have to read the file line by line, or load the entire file and then explode it by a linebreak and then loop through that (essentially the same).
Related
Good afternoon.
So i have this issue with CodeIgniter.
Im reading a file using the file helper of CI
$this->load->helper('file');
$data = read_file('file.txt');
The problem is that the line
$data = read_file('file.txt');
returns a string with all the content of the file and I need to read each line of the file to make some operations.
I just tried this:
$data_array= explode('\n',$data);
But when i do
sizeof($data_array);
its output is 1.
So. What is the special character that i need to use in order to properly explode the string?
Thanks in advance for the answers.
Use \n\r with double quotes (not single quotes):
$data_array = explode("\n\r", $data);
Line endings are depend on operation system, they can be \n, \r, \n\r or \r\n in different systems
So, you can either use file or mb_split with [\r\n]+ as pattern
I have a text file of approximately 25,000 lines. About 525kb.
Some lines have random text at the beginning.
Some have long strings of semicolons.
Some others only have three semi-colons and then a space and optionally more text on the same line. These are the lines I want to remove.
Here is a sample....
;;; Updated Time 20120706122706
;;; Generic DEveloper Output
;;; Some Random Comments
;;; I got some more...
;;; Yet another uneeded line
;;; Thanks for using StackOverflow <http://stackoverflow.com>, or...
;;; Not.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Banana Production
[Data_Release_Version]
Version=12586
Released=20120706122706
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Baseline Properties
[BaseLineProperties]
Comment=BaselineProperties
----- and so on.
Once it gets to the first line with 4 or more ; on the line, I need the rest of the file as there are no ";;; " lines.
Trying to find something fast instead of reading everything line and writing it back out if it doesn't match ";;; ".
File is ASCII (possibly UTF-8) text type file.
Any ideas?
Thank you for your time, assistance and knowledge.
What I would suggest is to use file_get_contents() and save file's contents in a variable as a string, then use explode() that string at every newline character, then in a foreach loop, use preg_match() to check if the line begins with 3 semicolons and a space, if it dosent, put it in another array named $output. After foreach, implode() $output and add a newline character and use file_put_contents() to print it in another file. Hope this helps :-)
code:
<?php
$string = file_get_contents($filename);
$array = explode("\n",$string);
foreach($array as $arr) {
if(!(preg_match("^;;;\s",$arr))) {
$output[] = $arr;
}
}
$out = implode("\n",$output);
file_put_contents($path,$out);
?>
Depends.. I would try to load into a string, then do a explode() with newline, so it's in array, then run a foreach with a skip on any that doesnt have strpos == 0 -AND- strpos !== false, you can put in a continue to skip to the next line if it doesnt match.
Another option, is to parse, and skip, or even using fseek, and such. Depends on alot of different factors to determine whats going to be fastest.
You can implode later on, and add the newlines back in, and then push out a file, and/or use line breaks. Depending where the output is supposed to go.
I think you gave the answer yourself:
Make a script that reads the input file line by line in a loop (while). It writes every line into an output file if two conditions are met: 1. a flag ("done") is FALSE and 2. the line does NOT start with ";;; " (not the blank). This removes those lines starting with three semicolons. Once you come about a line containing more semicolons you set the flag to TRUE, thus the remaining lines wil be copied without being examined.
How would I remove a line from the end of a string with PHP? Thanks.
You want to remove whitespace? Try trim(). It's close cousins ltrim and rtrim may be closer to what you want.
If you are looking to remove the last line is a string containing new line character (\n), then you'd do something like this ...
$someString = "This is a test\nAnd Another Test\nAnd another test.";
echo "SomeString BEFORE=".$someString."\n";
// find the position of the last occurrence of a \n
$firstN = strlen($someString) - strpos(strrev($someString), "\n");
// get rid of the last line
$someString = substr($someString, 0, $firstN);
echo "SomeString AFTER=".$someString;
if you're trying to remove a line from an end of a file, you could try using PHP's file() function to read the file (which places it into an array) and then pop the last element. This is assuming that php is recognizing the line endings in your file.
$subject = 'Text
written
with
lines';
echo preg_replace('/\\n[^\\n]*\\n?$/', '', $subject);
With feature, that there can be one special newline at the end which is ignored, 'cause it is often a good convention to let one at the end of a file (assuming you are reading string from a file).
I'm writing a PHP script that adds numbers into a text file. I want to have one number on every line, like this:
1
5
8
12
If I use file_put_contents($filename, $commentnumber, FILE_APPEND), the result looks like:
15812
If I add a line break like file_put_contents($filename, $commentnumber . "\n", FILE_APPEND), spaces are added after each number and one empty line at the end (underscore represents spaces):
1_
5_
8_
12_
_
_
How do I get that function to add the numbers the way I want, without spaces?
Did you tried with PHP EOL constant?
file_put_contents($filename, $commentnumber . PHP_EOL, FILE_APPEND)
--- Added ---
I just realize that my file editor does the same, but don't worrie, is just a ghost character that the editor places there to signal that there is a newline
You could try this
A file with EOL after the last number looks like:
1_
2_
3_
EOF
but a file without that last character looks like
1_
2_
3
EOF
where _ means a space character
You could try to parse the file contents using php to see what's inside
$lines = explode( PHP_EOL, file_get_contents($file));
foreach($lines as $line ) {
var_dump($line);
}
...tricky
pauls answer has the correct approach but he has a mistake.
what you need ist the following:
file_put_contents($filename, trim($commentnumber).PHP_EOL, FILE_APPEND);
the PHP_EOL constant makes sure to use the right line ending on mac, windows and unix systems
the trim function removes any newline or whitespace on both sides of the string.
converting to integer would be a huge mistake because
1. you might end up having zero, expecially because of white space or special characters (wherever they come from...)
2. ids dont necessarily need to be integers
Ohh Guys! Just Use
\r\n
insted of \n
There is nothing in the code you provided that would generate those spaces, unless $commentnumber already contains the space to begin with. If that is the case, simply use trim($commentnumber) instead.
There is also nothing in your code that would explain empty lines at the bottom of the file, unless $commentnumber can be an empty string. If that is the case, and you want it to output the number 0 instead, use intval($commentnumber).
Of course, you need only one of those two. If you want to preserve string-like content, use trim(); if you always want integers, use intval(), which already trims it automatically.
It is also possible that you accidentally wrote " \n" instead of "\n" in your actual code, but in the code you posted here it is correct.
annoyingregistration, what you have there is absolutely fine.
PHP_EOL and "\n" are exactly the same.
The code you provided theres nothing wrong with it so it must be the value of $commentnumber that has a space at the end of it. as stated, run your $commentnumber through the trim() function.
file_put_contents($filename, trim($commentnumber . "\n"), FILE_APPEND);
Good luck.
After reading your code and responses, I have come up with a theory...
Since I can't see that there's anything wrong with your code, how did you open and read the file? Did you actually open it in a text editor? Did you use a PHP script to do it? If so, open the file with a text editor and check that there are actually spaces at the end of each line. If there is actually is...well, ignore the rest of this answer, then. If not, just read on.
For instance, if you use something like this:
<?php
$lines = file($filename);
if($lines) // Error reading
die();
foreach($lines as $line)
echo $line."<br />";
Then you would always a whitespace at the end of the line because of the way file() work. Make sure each $line does not have a whitespace - such as a newline character - at the end.
Since HTML handles all whitespaces - spaces, tabs, newlines etc. - as spaces, if there is a whitespace at the end of $line, then those would appear as spaces in the HTML output.
Solution: use rtrim($line) to remove whitespaces at the end of the lines. Using the following code:
<?php
$lines = file($filename);
if($lines) // Error reading
die();
foreach($lines as $line)
echo rtrim($line)."<br />";
wouldn't have the same problems as the first example, and all spaces at the end of the lines would be gone.
its because each time you write to the file, the file is being finished, file_put_contents inserts an extra line break at the end
I'm creating a function which can accept a string which is either retrieved through file_get_contents() on a local text file, or something fetched from a url such as http://site.com/338383.txt.
The file will be a tab seperated file, with each item in the file being on its own line. Is it better to use \n or \r to explode() the string and get an array of each line?
I've noticed that in some cases \n doesn't work. I'd like a consistent way which works all the time. Any thoughts?
You can use file() to get the contents of the file as array with individual lines.
As duckyflip points out, you can use the file() function to get an array of file lines. However, if you still need to explode (for an unknown reason), you should use the PHP constant PHP_EOL instead of '\n' as this is cross-platform compliant.
Problem is that newline is defined differently for different "text/plain" encodings and platforms. The quick-and-dirty solution would probably be to use split and the regular expression "\r\n|\r|\n", however, it may break on some unicode files and it has no sense of "context". I.e. if you have a file where LF (\n) is used as a EOL marker, and there's some CRs there which should have been preserved, the CRs will be split on as well.
You can use preg_split () to explode by /\n\r|\n|\r/, and then trim () each item to make sure no trailing whitespace is remaining (if it’s appropriate).