Re: Searching for string in text file help?

From: Date: Tue, 02 Jul 2002 08:37:50 +0000
Subject: Re: Searching for string in text file help?
Groups: php.general 
Request: Send a blank email to php-general+get-104875@lists.php.net to get a copy of this message
>I'm trying to seach for a string that would occur about 10 lines into a text >file. I don't want to search the entire file, and I just want to know if the >string exsists or not, but I don't really know what I'm doing. This is what >I was trying, it occurs inside a loop that is listing the files in a >directory. > > $fp = fopen("$target_filename", "r"); > $contents = fgets("$fp","4096"); fgets will quite after 4096 characters *OR* a SINGLE line of text. You can either do "about 10" fgets() in a row, and check each one -- each one will be a single line, unless a line is over 4096 characters... *OR* you could just use fread() and assume the first line is only 4096 (or whatever number you feel is safe) characters total: $contents = fread($fp, 4096); > if(strstr("$contents", "$search_str")) > { > echo "<pre>"; > readfile("$target_filename"); > echo "</pre>"; > } Meta-comment -- If all you have is "$foo" then the quote marks are silly, and you can just use $foo. It will make your code a lot less "cluttered" looking. Works the same, for all practical purposes, but looks nicer. Technically, the "$foo" *might* cause the parser to waste a micro-second longer to figure out that "$foo" is "4" which is 4, instead of just going $foo is 4, but we're not talking measurable performance here, unless it's inside a loop with a zillion iterations... -- Like Music? http://l-i-e.com/artists.htm

« previous php.general (#104875) next »