note 83830 deleted from function.fseek by nlopess

From: Date: Sun, 15 Jun 2008 13:02:19 +0000
Subject: note 83830 deleted from function.fseek by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-140470@lists.php.net to get a copy of this message
Note Submitter: mike at mike-miles dot com ---- After not finding a good way to search a file backwards, I came up with this function, which uses fseek to scan the file backward byte by byte. It returns the position of the last occurance of the search string, or FALSE if not found. It's a case sensative search, but that could easily be changed. <?php function searchFromEnd($filename,$search){ if(file_exists($filename) && is_readable($filename)){ //first make sure that the file is there, and we can read it $fp = fopen($filename,'r'); //open the file for reading $size=strlen($search)-1; //get the length of the search string(minus the first character) $first=$search[0]; //get first element in string $file_size=filesize($filename); //size of the file $seek=$file_size-$size; //set seek pointer to end of the file - size of the string $found=false; //set found to FALSE while($seek>=0){ //while not past the begining of the file fseek($fp,$seek); //set file pointer to seek value $test=fread($fp,1); //read in the first byte from pointer if($test==$first && (($seek+$size) <= $file_size) ){ //if byte is same as the first string character, and back far enough in file for search length $test.=fread($fp,$size); //append enough characters to $test to make it same size as $search if(strcmp($test,$search)==0){ //if test value is what we're looking for $found=$seek; //return position; $seek=-1; //set pointer to -1 (exit loop); }else{ $seek--; //move back a byte } }else{ $seek--; //move back a byte } } fclose($fp); //close the file } return $found; //return FALSE or position of search string } ?> please, e-mail me and let me know if you find this function useful at all, or have any ideas on how to modify it

« previous php.notes (#140470) next »