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. Link to comment https://forums.phpfreaks.com/topic/198915-replacing-specified-line-in-file/ 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); Link to comment https://forums.phpfreaks.com/topic/198915-replacing-specified-line-in-file/#findComment-1044110 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. Link to comment https://forums.phpfreaks.com/topic/198915-replacing-specified-line-in-file/#findComment-1044118 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. Link to comment https://forums.phpfreaks.com/topic/198915-replacing-specified-line-in-file/#findComment-1044121 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? Link to comment https://forums.phpfreaks.com/topic/198915-replacing-specified-line-in-file/#findComment-1044130 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.