Re: how to use strstr() (or similar) on an array?

From: Date: Mon, 12 May 2003 11:20:39 +0000
Subject: Re: how to use strstr() (or similar) on an array?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-147296@lists.php.net to get a copy of this message
I'm *positive* this is not optimised code, but it seems pretty fast on a 10k, 210-line file I made up: <? $src_trm = "one two"; $searchWords = explode(' ',$src_trm); $handle = fopen("searchMe.txt", "r"); while(!feof($handle)) { $buffer = fgets($handle, 4096); foreach($searchWords as $word) { $pos = strpos($buffer,$word); if($pos === false) { // not found } else { $wordFound = 1; } } if($wordFound) { echo $buffer."<br />"; } $wordFound = 0; } fclose($handle); ?> Season to taste. I'm not sure how to tackle the highlighting problem, other than to ask if you *NEED* HTML tags in your search summary? Could this work? It's a lot cleaner and faster than any regular expressions: <? $src_trm = "one two"; $searchWords = explode(' ',$src_trm); $handle = fopen("searchee.txt", "r"); while(!feof($handle)) { $buffer = strip_tags(fgets($handle, 4096)); foreach($searchWords as $word) { $pos = strpos($buffer,$word); if($pos === false) { // not found } else { $wordFound = 1; $buffer = str_replace($word,"<b>{$word}</b>",$buffer); } } if($wordFound) { echo $buffer."<br />"; } $wordFound = 0; } fclose($handle); ?> To justify, google for example doesn't include any HTML tags in it's search results -- other than those which it places in there to highlight the key words. Justin on 12/05/03 10:15 PM, iliketheworld@gmx.ch (iliketheworld@gmx.ch) wrote: > i'm using the following script to scan each line of a text file for search > term $src_trm. only lines that contain the requested expression are printed. > > > $handle = fopen ($filename, "r"); > $i = 1; > > while ($i <= $total_lines_of_file) { > > $buffer = fgets($handle, 4096); > $buffer_raw = strip_tags($buffer); > > if(strstr($buffer_raw, $src_trm)) { > $buffer = preg_replace("/$src_trm/", "<b>$src_trm</b>", > $buffer); > echo $buffer; > } > > $i++; > } > fclose ($handle); > > > there are two problems: > > 1. > a user enters more than one word to search for: 'one two' is only found as > exact match and not if a line containes 'two' somewhere at the beginning and > 'one' somewhere at the end. > > maybe i should explode($src_trm) but then i don't know how to scan the file > for lines that contain all requested expressions. > > > 2. > $buffer = preg_replace("/$src_trm/", "<b>$src_trm</b>", > $buffer); > > this marks found words bold. unfortunately sometimes a word is also found > inside a html tag. is there a possibility to exclude tags from this > operation? > > > thanks a lot for your effort! > > > philipp rieger > http://www.ipdraw.org/ > > > > ps: thanks to don read and jim lucas for their helpful answers to "[PHP] > including() only given amount of lines"! >

« previous php.general (#147296) next »