Writing a tiny full-text search engine in PHP
Full-text search feels like magic until you build one. In about 200 lines of PHP you get an inverted index, BM25 ranking and results that are surprisingly good.
Every search engine starts with the same idea a library card catalog uses: instead of reading every document, you look up each word and get the list of documents that contain it.
Tokenize and index
php
function tokens(string $text): array
{
return preg_split('/[^\p{L}\p{N}]+/u', mb_strtolower($text), -1, PREG_SPLIT_NO_EMPTY);
}
foreach ($documents as $id => $text) {
foreach (array_count_values(tokens($text)) as $term => $count) {
$index[$term][$id] = $count;
}
}
Rank with BM25
BM25 rewards documents that contain a rare word often, but with diminishing returns, and it punishes very long documents a little. Two parameters, k1 and b, are all you need to tune.
What I would add next
Stemming, a prefix index for search-as-you-type and storing the index in SQLite FTS5 once it no longer fits into memory. That is where you stop writing a tiny engine and start using a real one.