Overwrite line in a file if it contains a string [duplicate] - php

This question already has answers here:
Overwrite Line in File with PHP
(7 answers)
Closed last year.
I am trying to overwrite a line in PHP in a file if it contains a certain string. When I write to my file, the lines aren't overwritten but are appended to the end. I am opening the file as 'a+', not 'w+' as I don't want the settings of other 'modes' to be removed.
The file, for example:
mode1Hello= 100
mode1Goodbye= 200
mode1Neutral= 300
mode2Hello= 100
mode2Goodbye= 200
mode2Neutral= 300
I have tried:
$myfile = fopen("test.txt", "a+") or die("Unable to open file!");
$lines = explode("\n", $myfile);
$exclude = array();
foreach ($lines as $line) {
if (strpos($line, 'mode1') !== FALSE) {
continue;
}
$exclude[] = $line;
}
echo implode("\n", $exclude);
$txt = "mode1Hello= 900\n";
fwrite($myfile, $txt);
$txt = "mode1Goodbye= 800\n";
fwrite($myfile, $txt);
$txt = "mode1=Neutral 700\n";
fwrite($myfile, $txt);
fclose($myfile);
But the test.txt file now reads:
mode1Hello= 100
mode1Goodbye= 200
mode1Neutral= 300
mode2Hello= 100
mode2Goodbye= 200
mode2Neutral= 300
mode1Hello= 900
mode1Goodbye= 800
mode1Neutral= 700
But I would like it to read:
mode1Hello= 900
mode1Goodbye= 800
mode1Neutral= 700
mode2Hello= 100
mode2Goodbye= 200
mode2Neutral= 300

$filename = 'test.txt';
$contents = file_get_contents($filename);
$lines = explode("\n", $contents);
foreach ($lines as &$line) {
if (str_starts_with($line, 'mode1Hello=')) {
$line = 'mode1Hello= 900';
} elseif (str_starts_with($line, 'mode1Goodbye=')) {
$line = 'mode1Goodbye= 800';
} elseif (str_starts_with($line, 'mode1Neutral=')) {
$line = 'mode1Neutral= 700';
}
}
unset($line);
$result = implode("\n", $lines);
file_put_contents($filename, $result);

Related

Create new txt files from each line of a txt file

I have a various txt files like ex: dictionary , each new line is term and then description. pipe delimited.
I have wrote simple script that actually reads each line and then creates (fwrite) new txt file named after term and description as a text of that file.
It works but I'm wondering if there is a better approach, one that takes special characters into account, buffer perhaps, Not sure where to start.
$file = fopen("test.txt", "r") or exit("Unable to open file!");
// Output a line of the file until the end is reached
while(!feof($file))
{
$line = fgets($file);
// making all lowercase - optional
$line = strtolower($line);
// take the first value before delimiter
$var = substr( $line, 0, strpos( $line, '|' ) );
// remove some characters - optional ( depends on a file structure and contents )
$var = str_replace("-", "", $var);
// what txt should be written into a each new file
$txt = str_replace("|", "", $line);
// name the file
$myfile = fopen("$var.txt", "w") or die("Unable to open file!");
// write
fwrite($myfile, $txt);
//close each
fclose($myfile);
}
//close
fclose($file);
UPDATE
$file = fopen("test.txt", "r") or exit("Unable to open file!");
// Output a line of the file until the end is reached
while(!feof($file))
{
$line = fgets($file);
// #sorak fix
$line = fgets($file);
$name = preg_replace('/[^0-9a-zA-Z]/', '',
explode('|', $line)[0]);
// making it lowercase - optional for each
$line = strtolower($line);
$name = strtolower($name);
// what txt should be written into a each new file
$txt = str_replace("|", " ", $line);
// name the file
$myfile = fopen("$name.txt", "w") or die("Unable to open file!");
// write
fwrite($myfile, $txt);
// action echo
echo "$myfile - $name - $txt </br>";
//close each
fclose($myfile);
}
//close
fclose($file);
Since last update contained some duplicate code lines/bugs that caused skipping every other line :) I'm posting new fixed and bit upgraded version.
// this utility is for creating multiple names.txt files from separate lines in original.txt file
// format for original file is: is name|text
// increase memory limit to 32M
ini_set('memory_limit','32M');
// increase 1440 seconds = 24 minutes
ini_set('max_execution_time', 1440);
$file = fopen("original.txt", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
// #sorak fix
//$line = fgets($file);
$name = preg_replace('/[^0-9a-zA-Z]/', '',
explode('|', $line)[0]);
// making it lowercase - optional for each
$line = strtolower($line);
$name = strtolower($name);
$filename = $name . ".txt";
// what text should be written into a each new file
// change pipe separator if needed
$txt = str_replace("|", " ", $line);
// set values
$myfile = fopen($filename, "a") or die("Unable to open file!");
$dir = "/example.com/could_be_dynamic_folder_name";
// write
fwrite($myfile, $txt);
// chmod($dir,0777); optional if creation of dir is from GET/other value and not in the same parent
// action echo
echo "$myfile </br>";
echo "$dir/$filename </br>";
echo "$txt </br></br>";
// chmod
chmod($dir,0777);
chmod("$dir/$filename",0666); // remember to set this script to 0666
}
fclose($file);
} else {
// error echo
echo "something went wrong, error";
}
Works like a charm now. Case closed.
$line = fgets($file);
$name = preg_replace('/[^0-9a-zA-Z]/', '',
explode('|', $line)[0]);
Explode makes splitting up the string easier, and with the [0] we grab the first piece. That preg_replace instruction just removes all characters that aren't letters or numbers.

in php how to delete text line in txt / notepad file when txt reaches 100 lines

How to delete / clear lines of data if it reaches 100th line. I checked some examples, but it is not working.
I need to check the number of the line end if it reaches line number 100, delete or clear all in that text file.
The following code is taken from an example, but this is also not working:
<?php
$text = "log.txt";
$lines = explode("\n", $text);
$lines = array_slice($lines, 0, 10); //10 is how many lines you want to keep
$text = implode("\n", $lines);
?>
Something like this: you will need to take it and fit it to your application, but I think this is what you are looking for.
//Count lines
$file="largefile.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
//Remove lines
if ($linecount ==100)
{
$lines = file($file, FILE_IGNORE_NEW_LINES);
$remove = "balblalbllablab";
foreach($lines as $key => $line)
if(stristr($line, $remove)) unset($lines[$key]);
$data = implode('\n', array_values($lines));
$file = fopen($path);
fwrite($file, $data);
fclose($file);
}

How to insert string before last line?

I saw using fseek to insert string before last line this question, but this isn't solving my problem. I not use "?>" tag. Php version PHP 5.4
example line1
example line2
//i need insert here
lastline $eg};
My code is working but this is adding empty lines after all lines :
$filename = 'example.php';
$arr = file($filename);
if ($arr === false) {
die('Error' . $filename);
}
array_pop($arr);
file_put_contents($filename, implode(PHP_EOL, $arr));
/// I'm deleting last line here
$person = "my text here\n";
file_put_contents($filename, $person, FILE_APPEND);
$person = "andherelastline";
file_put_contents($filename, $person, FILE_APPEND);
//and then add again here
$file = "tmp/saf.txt";
$fc = fopen($file, "r");
while (!feof($fc)) {
$buffer = fgets($fc, 4096);
$lines[] = $buffer;
}
fclose($fc);
//open same file and use "w" to clear file
$f = fopen($file, "w") or die("couldn't open $file");
$lineCount = count($lines);
//loop through array writing the lines until the secondlast
for ($i = 0; $i < $lineCount- 1; $i++) {
fwrite($f, $lines[$i]);
}
fwrite($f, 'Your insert string here'.PHP_EOL);
//write the last line
fwrite($f, $lines[$lineCount-1]);
fclose($f);

Read files for part by part for 1000 bytes in PHP

I want to read a file line by line and add it into a variable till its string length is 1000 bytes . The file is relatively large,
Hence, what I am doing is
if(file_exists($file)
{
$fh = fopen($file, "r");
while(!feof($fh) or strlen($chunk) < 10001)
{
$line = fgets($fh, 1000);
$chunk = $chunk."**".$line;
}
}
Issue is how does I store each chunk into an array index till I encounter end of file ?
What about this:
if(file_exists($file)
{
$fh = fopen($file, "r");
$chunks = array();
while(!feof($fh) or strlen($chunk) < 10001)
{
$line = fgets($fh, 1000);
// add line to the buffer
$chunks []= $line;
}
}
? Or am I missing something?

How can I read 30MB text file using php script?

Hi I do have a text file with size of upto 30MB I would like to read this file using PHP loop script
$lines = file('data.txt');
//loop through each line
foreach ($lines as $line) { \\some function }
Is there any way? I want open it for reading php doesnt allow me to open a 30MB file.
You could read it line by line like this:
$file = fopen("data.txt", "r") or exit("Unable to open file!");
while(!feof($file)) {
// do what you need to do with it - just echoing it out for this example
echo fgets($file). "<br />";
}
fclose($file);
Read line by line using:
$handle = fopen ( "data.txt", "r" );
while ( ( $buffer = fgets ( $handle, 4096 ) ) !== false ) {
// your function on line;
}
If it is suitable for you to read the file piece-by-piece you can try something like this
$fd = fopen("fileName", "r");
while (!feof($fd)) {
$buffer = fread($fd, 16384); //You can change the size of the buffer according to the memory you can youse
//Process here the buffer, piece by piece
}
fclose($fd);

Categories