PHP: Opening .txt file, reading line by line, removing (YEAR) - php

I am looking for a suggestion on this:
I have a text file called movies.txt with about 900 lines, which contains one movie name per line. However, I would like to remove the year the movie has been released using PHP (which I am new to)
The format is basically:
A Nous la Liberte (1932)
About Schmidt (2002)
Absence of Malice (1981)
Adam's Rib (1949)
Adaptation (2002)
The Adjuster (1991)
The Adventures of Robin Hood (1938)
Affliction (1998)
The African Queen (1952)
So I am looking for a way to open the text file, reading it line by line and removing the (YEAR) values while also removing the space before the (YEAR).
Then I would like to save it as newmovies.txt
Would be great if you could show and explain me a solution that works for my needs. I am still very new to PHP (started a week ago) so it's all still magic to me.

You can read a file line-wise using the file() function. Then foreach over that and strip lines until the opening parenthesis.
For example
foreach (file($fn) as $line) {
$output[] = strtok($line, "(");
}
You may need to trim the extra space and add linebreaks again.
So a regex might be simpler and also asserts some structure without blindly cutting things off:
$text = file_get_contents($fn);
$text = preg_replace('/\s*\(\d+\)/m', '', $text);
# \s* is for spaces and \d+ is a placeholder for numbers
Then save that back.

<?php
$toWrite = "";
$handle = #fopen("input.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$toWrite .= preg_replace('/\(\d+\)/', '', $buffer) . "\n";
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
file_put_contents("input.txt", $toWrite);
}
?>

Related

simple date visitor counter counting the text lines

i'm trying to make visitors count without sql with simple php code
counting the date list
i have log file called visits.log contains
2018-06-28
2018-06-28
only two lines
when i try to echo the lines gives me 5 i donno how but when i try to replace the log with something like
test
test
gives me 2 visitors
note: the text file doesn't contain empty space lines.
my php code
<p class="">Views today</p>
<span class=""><?php
$file="../../visitors.log";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
echo $linecount-1;
?></span>
my adding lines code
$line = date('Y-m-d') . " - $_SERVER[REMOTE_ADDR]";
file_put_contents('visitors.log', $line . PHP_EOL, FILE_APPEND);
Try the below code to get number of lines
$no_of_lines = count(file($file));
thanks for help guys my script was adding a hidden empty lines and i deal with it with replace()
replacing the empty lines to remove it

Why does it add the text at the beginning of next line, and not the end of the right one?

Needed solution:
I am working with a simple PHP script that should:
Add "value4:::" at the end of the first line in a file
Add ":::" at the end of all the next lines
I am novise in programming, and have sit here for two days trying to figure this out. Might be a little detail, or it might be totally wrong way of doing this task.
It might be wrong way to do this, or may be a regex problem? I really don't know.
I kindly ask you to help me with the solution.
Information:
The file newstest.db looks like this:
ID:::value1:::value2:::value3:::
1:::My:::first:::line:::
2:::My:::second:::line:::
3:::Your:::third:::line:::
And using this php script I'd like to make it look like this:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Problem:
So far I have almost got it, but I am confused to why it adds the "value4:::" to the beginning of the second line, and then add ":::" at the beginning (not end) of all of the rest of the lines.
So I get a file that looks like this:
ID:::value1:::value2:::value3:::
value4:::1:::My:::first:::line:::
:::2:::My:::second:::line:::
:::3:::Your:::third:::line:::
I thought that:
$lineshere = 'Some text here:::';
$lines1 = $linehere.'value4:::';
would output "Some text here:::value4:::"
May be the problem is due to this way of adding line after line?
$lines = '';
$lines.= 'My test';
$lines.= ' is here';
echo $lines;
I am a novise in programming, so I might have used totally wrong functions tec to make this work.
But in this case it seams to add a space or line break/ line end in the wrong place.
My try on this solution:
<?php
// specify the file
$file_source="newstest.db";
// get the content of the file
$newscontent = file($file_source, true);
//set a start value (clear memory)
$lines ='';
// get each line and treat it line by line.
foreach ($newscontent as $line_num => $linehere) {
// add "value4:::" at the end of FIRST line only, and put it in memory $lines
if($line_num==0) {
$lines.= $linehere.'value4:::';
// Just to see what the line looks like
//echo 'First line: '.$lines.'<br /><br />';
}
// then add ":::" to the other lines and add them to memory $lines
if($line_num>0) {
$lines1 = $linehere.':::';
$lines.= $lines1;
//just look at the line
//echo 'Line #'.$line_num.': '.$lines1.'<br /><br />';
}
}
//Write new content to $file_source
$f = fopen($file_source, 'w');
fwrite($f,$lines);
fclose($f);
echo "// to show the results ar array<br /><br />";
$newscontentlook = file($file_source, true);
print_r(array_values($newscontentlook));
?>
This is actually very easy to achieve with file_get_contents and preg_replace, i.e:
$content = file_get_contents("newstest.db");
$content = preg_replace('/(^ID:.*\S)/im', '$1value4:::', $content);
$content = preg_replace('/(^\d+.*\S)/im', '$1:::', $content);
file_put_contents("newstest.db", $content);
Output:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Ideone Demo
the function file() gives you the file in an array with each line being an element of the array. Each ending of the line (EOL) is included in the elements. So appending text to that line will be after the EOL, and thus effectively on the beginning of the next line.
You can either choose to not use file() and explode the text yourself on the EOL, so the EOL is no longer part of the array element. Then edit the elements, and implode the array again.
Or fopen() the file, and fread() through it yourself. The latter option is preferred, as it won't load the entire file into memory at once.
I think the problem is in your loop through the lines read by file() function:
foreach ($newscontent as $line_num => $linehere) {
...
$linehere contains a newline at the end, so you should simply chop it before using it:
foreach ($newscontent as $line_num => $linehere) {
$linehere = chop($linehere);
...
If you don't chop the line contents, when you concatenate a string to it, you'll get:
LINE_CONTENTS\nSTRING_ADDED
which, when printed, will be:
LINE_CONTENTS
STRING_ADDED
Hope this helps...

Removing spaces from a text file using PHP

I need to add itens from a text file, into a MySQL database, to do that i'm trying to use PHP to read the file and insert everything into the database, the problem is that the text file, has 2 itens per line, divided by spaces, something like this:
teste.txt
ITEM1 ITEM2
ITEM323 ITEM4
ITEM54 ITEM6
ITEM34234 ITEM8
I'm trying to remove the spaces using explode, but because the number of spaces, is random, i cannot do that. This is my Code:
$handle = #fopen("teste.txt", "r"); //read line one by one
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 4096); // Read a line.
list($a,$b)=explode(" ",$buffer);//Separate string by Spaces
//values.=($a,$b);// save values and use insert query at last or
echo $a;
echo "<br>";
echo $b . "<br>"; // NEVER echoes anything
}
What should i do?
You can insert a method to change multiple spaces to one:
$buffer = preg_replace('/\s+/',' ',$buffer);
Right before exploding it:
$buffer = fgets($handle, 4096); // Read a line.
$buffer = preg_replace('/\s+/',' ',$buffer);
list($a,$b)=explode(" ",$buffer);//Separate string by Spaces
You can use preg_replace() to perform a regular expression:
$buffer = preg_replace("/\ +/", " ", fgets($handle, 4096));

PHP: uploading text file to page, which shows new line for each text entry, and sorted alphabetically

I'm using PHP and I want to upload a text file, with the output / view showing each line from the text file on a new line (so exactly as it is displayed in the text file).
However, I also want the text file to be sorted alphabetically.
I have working code that uploads the file on each new line, and sorts by upper case, then lowercase - using the sort function
And I have code which sorts it alphabetically (regardless of case), but unfortunately the lines are grouped together, and not separated as I want them to be. - using the natcasesort
I've tried numerous things but not getting anywhere, so hoping someone can help either put the two together, or let me know what I need to do to either piece of code which will make each line show on a new line.
1st CODE NEEDS TO BE SORTED ALPHABETICALLY REGARDLESS OF UPPER/LOWERCASE
2nd CODE NEEDS TO SHOW THE LINE BREAKS
<?php
$file = file("users.txt");
sort($file);
for($i=0; $i<count($file); $i++)
{
$states = explode(",", $file[$i]);
echo $states[0], $states[1],"<br />";
}
?>
<?php
$filename="users.txt";
$lines = array();
$file = fopen($filename, "r");
while(!feof($file)) {
$lines[] = fgets($file,4096);
}
natcasesort($lines);
print_r($lines);
fclose ($file);
?>
You must use
$text = implode("<br />", $lines);
echo $text
It would glue the array and pasting a <br /> in every new line. Of course, if it is being printed in HTML, if not use the carrier \n instead.
And your code would look like:
.
.
.
while(!feof($file)) {
$lines[] = fgets($file,4096);
}
natcasesort($lines);
$text = implode("<br />", $lines);
print_r($text)
.
.
.

How to tell explode to ignore line feeds?

I have written some small code to read in a flat text file and display it. My issue is that one of the fields has alot of text in it and also some line returns. My code is using the line return is a delimiter and moving onto the next record.
How can I tell it to only split by the delimiter and ignore line returns?
Sample code I am using:
$delimiter = chr(1);
$fp = fopen('app2','r');
if (!$fp) {echo 'ERROR: Unable to open file.</table></body></html>'; exit;}
$loop = 0;
while (!feof($fp)) {
$loop++;
$line = fgets($fp,2048); //use 2048 if very long lines
$field[$loop] = explode ($delimiter, $line);
echo '
<tr>
<td>'.$field[$loop][0].'</td>
<td>'.$field[$loop][1].'</td>
<td>'.$field[$loop][2].'</td>
<td>'.$field[$loop][3].'</td>
<td>'.$field[$loop][4].'</td>
<td>'.$field[$loop][5].'</td>
<td>'.$field[$loop][6].'</td>
<td>'.$field[$loop][7].'</td>
<td>'.$field[$loop][8].'</td>
<td>'.$field[$loop][9].'</td>
<td>'.$field[$loop][10].'</td>
<td>'.$field[$loop][11].'</td>
<td>'.$field[$loop][12].'</td>
<td>'.$field[$loop][13].'</td>
<td>'.$field[$loop][14].'</td>
<td>'.$field[$loop][15].'</td>
<td>'.$field[$loop][16].'</td>
</tr>';
$fp++;
}
fclose($fp);
?>
You can see what it is doing here http://www.smartphonesoft.com/fred/xmlfeed/test/itunes_to_mysql.php
You can paste your textfile into one $var, by jaust adding all with .= , as long as your file is not 2GB large.
Note: string can be as large as 2GB.

Categories