This is a discussion on delete line within the PHP General forums, part of the PHP Programming Forums category; I've been looking and haven't found anything on this. How do you open a file then select a ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
> I've been looking and haven't found anything on this. How do you open a file
> then select a line and delete that line? Warning: untested. This is just to give you a general idea. $fileName = "blah.txt"; $lineToDelete = "Delete this line"; $fileArray = file( $fileName ); if(( $lineNum = array_search( $lineToDelete, $fileArray )) && ( $lineNum > 0 )) { $firstPartArray = array_slice( $fileArray, 0, $lineNum ); $secondPartArray = array_slice( $fileArray, $lineNum + 1 ); $fileArray = array_merge( $firstPartArray, $secondPartArray ); $fp = fopen( $fileName, w+ ); fwrite( $fp, implode( '\n', $fileArray )); } I'm not too sure if the array_merge() is going to work. I am not sure if the array_slice() maintains the current key in the new array. If it doesn't, then you'll end up with jumbled file contents. If this is the case, then you'll just need to iterate through both new arrays in turn and store the values in a new array. $newFileArray = array(); foreach( $firstPartArray as $value ) { $fileArray[] = $value; } foreach( $secondPartArray as $value ) { $fileArray[] = $value; } There might be a better way to do this, but that's the only way that I can think of personally. Chris |
![]() |
| Thread Tools | |
| Display Modes | |
|
|