note 27450 deleted from function.fgets by sniper

From: Date: Sat, 08 Feb 2003 20:11:17 +0000
Subject: note 27450 deleted from function.fgets by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-43662@lists.php.net to get a copy of this message
Here's a class that I wrote for highlighting a desiered word inside a text file. It also doesn't have the problem that the first posts discussed about ( using fgets without considering a big line that falls out of your range might split a query word and you do not find it anymore) [pre] class findWord { var $fileName; var $queryWord; var $color; # The color of queryWord in output. var $fp; # file pointer. var $lines = array(); var $Output; var $buffSize; # The size of buffer. function findWord( $fileName, $queryWord, $color = "red", $buffSize = 1024) { if ( file_exists($fileName) ) { $this->fileName = $fileName; $this->fp = fopen($this->fileName, "r"); $this->queryWord = $queryWord; $this->color = $color; $this->buffSize = $buffSize; $this->lines = $this->readLines( $this->fp, $this->buffSize); $this->Output = $this->queryLines( $this->lines, $this->queryWord, $this->color); $this->showFile( $this->Output); } else { die("Program dies : Invalid file name."); } } function readLines( $fp, $buffSize) { # This little line saves the program when a word is at the # junction between two chunks, i.e. if a word doesn't fit # in one line and fgets reaches its length sooner than the # CR and it breaks the line in the middle of our queryWord. #$buffSize += $buffSize - ( strlen($this->queryWord) - 1 ); $lines = array(); $count = 0; while ( !feof( $fp) ) { $lines[$count] = fgets( $fp, $buffSize); if ( $count != 0 ) { $temp = $lines[$count-1]; if ( strlen($temp) >= $buffSize-1 && $temp[strlen($temp)-1] != "\n" ) { $lines[$count-1] .= $lines[$count]; # coz when we increment $count below, it actually doesn't get incremented! --$count; } } $count++; } return $lines; } function queryLines( $lines, $queryWord, $color) { foreach ( $lines as $key => $val) { $holder = explode( $queryWord, $val); $lines[$key] = implode( "<font color=$color>$queryWord</font>", $holder); } return $lines; } function showFile( $outPut) { foreach ( $outPut as $val) print "$val <br>"; } } # An example instantiation of this class, note that the buffSize # isn't important anymore, since by pasting all the returned # strings of fgets together till we find each line exactly ( not # the chunks that fgets make if the buffSize be less than a line # length ), we can populate our array by lines and then search # each slut! for the queryWord. $ourFile = new findWord("search.txt", "hello", "blue", 5); [/pre]

« previous php.notes (#43662) next »