wwfc_barmy_army Posted April 18, 2010 Share Posted April 18, 2010 Hello Guys. I have this PHP code to get a line from a file that starts with the word 'Number'. There is only 1 line with this in: while( ! feof($file)) { $line = fgets($file); if (preg_match("/^Number\b/", $line)) { echo $line; } } How would I go about replacing just that line? Any suggestions? Thanks. Quote Link to comment Share on other sites More sharing options...
SaMike Posted April 18, 2010 Share Posted April 18, 2010 Try this: $line = preg_replace("/^Number\b/", "Replace with this", $line); Quote Link to comment Share on other sites More sharing options...
wwfc_barmy_army Posted April 18, 2010 Author Share Posted April 18, 2010 I didn't include the whole code and it may change your answer: $file = fopen("myfile","r"); while( ! feof($file)) { $line = fgets($file); if (preg_match("/^Number\b/", $line)) { echo $line; } } fclose($file); If i'm not mistaken it's opening it with read access, so I don't think that would work. Any other ideas? Thanks. Quote Link to comment Share on other sites More sharing options...
SaMike Posted April 18, 2010 Share Posted April 18, 2010 Oh, you should first open the file and read it's contents, then clear it, then change the line from variable you read the contents into and then write new edited content back. I dont think its possible to edit single line from flatfile. Quote Link to comment Share on other sites More sharing options...
litebearer Posted April 18, 2010 Share Posted April 18, 2010 Just a passing thought (PSUEDO code)... $lines = file($file_name); $rows = count($lines); $needle = "Number"; $new_content = "Whatever"; $i = 0; while($i<$rows) { if $needle in $line[$i]; $line[$i] = $new_content; $i = $rows; } $i ++; } write the $lines array back to a file make sense? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.