Review your favorite Linux distribution.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 01-28-2007, 01:42 PM   #1
LQ Newbie
Registered: Jan 2007
Posts: 2

Rep: Reputation: 0
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.


$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!

Old 01-28-2007, 01:46 PM   #2
Senior Member
Registered: Dec 2003
Location: Trondheim, Norway
Distribution: Debian and Ubuntu
Posts: 1,439

Rep: Reputation: 440Reputation: 440Reputation: 440Reputation: 440Reputation: 440

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"
Old 01-28-2007, 02:43 PM   #3
LQ Newbie
Registered: Jan 2007
Posts: 2

Original Poster
Rep: Reputation: 0
Thank you!

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

I appreciate the help.



Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
bash shell script read file line by line. Darren[UoW] Programming 57 04-17-2016 07:07 PM
C: fread to read a file line by line until the end Blue_muppet Programming 2 09-19-2008 10:42 AM
read line by line form text file in java. spank Programming 1 10-18-2006 03:46 PM
Script to read line by line from a file kushalkoolwal Programming 20 01-27-2006 05:17 AM
linux scripting help needed read from file line by line exc commands each line read atokad Programming 4 12-26-2003 11:24 PM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 12:03 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration