LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   php - Read file line by line and change a specific line. (https://www.linuxquestions.org/questions/programming-9/php-read-file-line-by-line-and-change-a-specific-line-523519/)

anrea 01-28-2007 12:42 PM

php - Read file line by line and change a specific line.
 
pseudo code:

defined_string = "Anrea"
replace_string = "Anonymous"

Open file "xyz.txt"
Read one line.
Compare line to a defined_string
If they match change line to replace_string
Loop to check for more, til end of file.


I've been staring at this code too long! Does anyone see anything wrong? I did have this working, but seem to have done something to make it quit working.

<?php

$findThis = "Anrea";
$handle = @fopen("xyz.txt", "r"); // Open file form read.

if ($handle) {
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 4096); // Read a line.
if ($buffer <> "Anrea") // Check for string.
{
echo "$buffer"; // If not string show contents.
} else {
$buffer = $findThis; // If string, change it.
echo "$buffer"; // and show changed contents.
}
}
fclose($handle); // Close the file.
}

?>

Thanks for any help!

Anrea :scratch:

Guttorm 01-28-2007 12:46 PM

Hi

fread reads a line - but the last "\n" character is also included in the string.

So you need to call chop or trim on $buffer - or compare it to "Anrea\n"

anrea 01-28-2007 01:43 PM

Thank you!
 
Perfect! I knew it had to be something simple....

I appreciate the help.

Anrea


All times are GMT -5. The time now is 03:41 PM.