Re: delete line

From: Date: Tue, 12 Aug 2003 15:54:55 +0000
Subject: Re: delete line
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-159290@lists.php.net to get a copy of this message
> 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

« previous php.general (#159290) next »