2

I would like to know which is the fastest way to find a string in a file using PHP. I have been told than the quickest way to read a file was using file() function, but to find a string in the whole file I will have to do a foreach. Whereas if I use file_get_contents or something, I just have to do a strpos() on the file.

The point is not to know if strpos() is the faster (I think it is). But to know if, is it better to get all the content of the file and do strpos() ONLY ONCE, or to get the file line by line and do strpos() foreach line until I find my value (or until the end if the value is not found).

Ari Zala
  • 23
  • 5
  • 5
    Possible duplicate of [php - Is strpos the fastest way to search for a string in a large body of text?](http://stackoverflow.com/questions/3874063/php-is-strpos-the-fastest-way-to-search-for-a-string-in-a-large-body-of-text) – revo Jul 28 '16 at 08:46
  • 1
    So create a test file and share your results. – u_mulder Jul 28 '16 at 08:46
  • @revo, for me strpos() is the fastest way, but the thing is : Is it better get all lines (using file() function) and strpos() on each line, or to get the whole file and do strpos() once on it. – Ari Zala Jul 28 '16 at 08:51
  • I'd argue the fastest way would be a loop with `fgets` and a`strpos` on each line (assuming the text doesn't span many lines) that way if the text is near the top of the file you won't have to read much of it. – apokryfos Jul 28 '16 at 09:01
  • @apokryfos the file contains approximately 5000 lines (2,3Mo) – Ari Zala Jul 28 '16 at 09:07
  • file size is definitely a factor - try to do `file_get_contents` for a file with 2GB size – Elzo Valugi Jul 28 '16 at 09:10
  • Caring about speed, the fastest way to eat a cake is when you have the whole cake baked and ready (*`file_get_contents()`*). But that's not the whole story. On big cakes, you may encounter *small-mouth* problems (*memory shortage*). You wouldn't like to kill your *mouth* for the sake of being quick in eating. Be aware of your cakes and choose a wise method of eating. – revo Jul 28 '16 at 09:18
  • @revo I don't understand the metaphor but now I want cake. – apokryfos Jul 28 '16 at 09:22
  • *Greed is the key to trouble.* – revo Jul 28 '16 at 09:25

0 Answers0