note 83830 added to function.fseek

From: Date: Fri, 13 Jun 2008 20:12:51 +0000
Subject: note 83830 added to function.fseek
Groups: php.notes 
Request: Send a blank email to php-notes+get-140420@lists.php.net to get a copy of this message
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 ---- Server IP: 64.71.164.2 Probable Submitter: 72.72.82.169 ---- Manual Page -- http://www.php.net/manual/en/function.fseek.php Edit -- https://master.php.net/note/edit/83830 Del: integrated -- https://master.php.net/note/delete/83830/integrated Del: useless -- https://master.php.net/note/delete/83830/useless Del: bad code -- https://master.php.net/note/delete/83830/bad+code Del: spam -- https://master.php.net/note/delete/83830/spam Del: non-english -- https://master.php.net/note/delete/83830/non-english Del: in docs -- https://master.php.net/note/delete/83830/in+docs Del: other reasons-- https://master.php.net/note/delete/83830 Reject -- https://master.php.net/note/reject/83830 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#140420) next »