title: Fastest way to search for whole words in 20mb flat file database (PHP)
body: <p>I have 20MB flat file database with about 500k lines, only <code>[a-z0-9-]</code> characters are allowed, average 7 words in line, no empty or duplicate lines:</p>
  
  <p>Flat file database:</p>
  
  <pre><code>put-returns-between-paragraphs
  for-linebreak-add-2-spaces-at-end
  indent-code-by-4-spaces-indent-code-by-4-spaces
  </code></pre>
  
  <p>I'm searhcing for <code>whole words only</code> and extracting <code>first 10k results</code> from this db.</p>
  
  <p>So far this code work ok if the 10k matches are found in let's say first 20k lines of the db, but if the word is rare, the script must search all 500k lines and this is 10 times slower.</p>
  
  <p>Settings:</p>
  
  <pre><code>$cats = file("cats.txt", FILE_IGNORE_NEW_LINES);
  $search = "end";
  $limit = 10000;
  </code></pre>
  
  <p>Search:</p>
  
  <pre><code>foreach($cats as $cat) {
      if(preg_match("/\b$search\b/", $cat)) {
          $cats_found[] = $cat;
          if(isset($cats_found[$limit])) break;
      }
  }
  </code></pre>
  
  <p>My php skills and knowledge are limited, I cannot and don't know how to use sql, so this is the best I can do it, but I need some advices:</p>
  
  <ul>
  <li>Is this the right code to do it, foreach and preg_match are problem?</li>
  <li>Should I split large file into smaller files, if yes what sizes?</li>
  <li>And in the end, will sql be faster and how much? (Option for the future)</li>
  </ul>
  
  <p>Thanks for reading this and sorry for bad English, this is my 3rd language.</p>