View Full Version : Search a file/more efficient to use a string or array?

05-02-2006, 03:58 PM

I'm aware PHP can read the entire contents of a file into a string then from there it's possible to search that string for some data.
And I'm also aware that PHP can read the entire contents of a file into an array then from there it's possible to search that array for some data.

But can PHP search a file (such as a .txt or .html file) for a string of data?
If not, then I guess I'm stuck with the first two options I listed. In that case, lets say I have a .txt file with a bunch of text in it. I want to locate a specific phrase within that text file. Is it more efficient (faster results) to read the contents of that .txt file into a string or an array? Then perform the search.

Thanks in advance,


05-02-2006, 04:18 PM
I don't think either is that efficient, if you want to work on the file directly you would be better off using the tools available to the OS, e.g. on *NIX you could use grep via exec()

exec("grep $searchword file.txt",$yaks);

the better solution would be to parse the text file for keywords when it is first created, store that in a DB and search the DB instead.

Aruna Attanayak
05-16-2006, 12:51 PM
//you can easily do it through thse functions
$file = fopen($fileatt,'r'); //opening the file for reading
$data = fread($file,filesize($fileatt)); // read content of file into variable $data
fclose($file); //close file handler

//after that you can use $data varible for searching matching string
substr_count() function may help you see manual for more details