Modernizing PHP's String-Comparison FunctionsModernizing PHP’s String-Comparison Functions

Every PHP developer has written if ($a === $b) and patted herself on the back, since this is much better than if ($a == $b). Most of the time, that’s the right answer. Then, a little change comes to the requirements: can you find users whose names are like “Smythe”?. And suddenly you’re reaching for the darker corners of the PHP manual.

The manual has four functions for that job: soundex(), metaphone(), levenshtein(), and similar_text(). They are not recent: the algorithms themselves date from 1918 (Soundex), 1965 (Levenshtein), 1990 (Metaphone), and 1993 (similar_text). PHP isn’t deprecating them, though the community has been quietly moving on. You should know what to reach for instead.

This post walks the full span: from the most rudimentary comparison == at one end, up to larger pieces of text, where you actually want an actual diff at the other: we’ll stop at the four native functions along that way.

The baseline: ==

This is a direct comparison. Either the bytes match or they don’t.

if ($input === 'expected') { /* ... */ }

Use ===, not ==, unless you actively want "0" == false to be true. It’s a classic PHP bug, and the community has spent over a decade trying to talk people out of. We are still at it.

== is the right answer when you have an exact-match contract: user IDs, enum values, hashes, normalized slugs.

When you need the same value, but still a bit different, you’re entering a new world. Welcome to the fuzzy part of the manual.

soundex(), from Russell, 1918

The algorithm

Take a word, keep the first letter, replace every following letter with a digit by sound group: 1 is for B/F/P/V, 2 is for C/G/J/K/Q/S/X/Z, etc; collapse adjacent duplicates, pad with zeros to four characters. “Robert” and “Rupert” both become R163. “Tymczak” becomes T522.

Reference: Robert C. Russell’s US patent 1,261,167 (1918), NARA Soundex coding guide, Soundex, Wikipedia.

The PHP function soundex(string $string): string

It is an internal function, written in C inside PHP’s standard extension. It is English-only, as the figure mapping would change from language to language. It is also limited to four characters out, and it has no options.

The catches

It was built for English-language surnames and indexing records by ear. It handles other languages poorly. “Lee”, “Liu”, and “Li” all collapse to L000. It also has a well-known edge case: “Ashcraft” is coded A261 under the standard American rules, where H and W don’t separate letters with the same code, but PHP returns A226, because PHP treats the H as a separator. Results differ between implementations, so don’t rely on exact codes for ambiguous names.

Modern replacements

If you’re calling soundex() in 2026, you probably want to look at Double Metaphone.

metaphone() by Philips, 1990

This has some repeat from the previous one, as they overlap in usage.

The algorithm

metaphone is like Soundex but smarter about English phonology. It drops silent letters, such as kin kn, b in mb, knows that tion is X, so “nation” comes out as NXN. It encodes vowels only when they’re pronounced. The output has variable length, not fixed four chars. This way, “Thompson” becomes 0MPSN, “Thomson” becomes 0MSN: the initial TH is coded as 0 or theta, which is surprising when you don’t know it.

Reference: Lawrence Philips, Hanging on the Metaphone, Computer Language, December 1990; see Metaphone, Wikipedia for an overview.

The PHP function

metaphone(string $string, int $max_phonemes = 0): string. The optional $max_phonemes argument caps the length of the returned key. Note that the function’s current behaviour, including the $max_phonemes parameter, is documented in the manual; PHP 8.0 changed its failure behaviour, not its basic signature.

The catch

It’s a single Metaphone. Philips himself published Double Metaphone ten years later because single Metaphone’s English bias was a known problem.

Modern replacements

  • Double Metaphone, obviously. See the packages above.
  • Metaphone 3: not triple, but still, the most accurate; the reference is commercial and no free Composer package offers it yet.
  • Caverphone, along with Caverphone 2: it is built specifically for the New Zealand electoral roll and it outperforms Metaphone on some accents. I found no Composer package for it. It is just a reminder that you may have to dig a local algorithm for your particular culture. Don’t forget to publish it. Reference: Caversham Project, University of Otago and Caverphone, Wikipedia.

Use Double Metaphone unless you have a specific reason not to.

levenshtein(), by Levenshtein, 1965

The algorithm

It is the minimum number of single-character insertions, deletions, and substitutions to turn one string into another. “kitten” → “sitting” is 3: k -> s, e -> i, add g. It is classic, easy to understand, a bit harder to implement. Reference: Levenshtein distance, Wikipedia.

The PHP function

levenshtein(string $string1, string $string2, int $insertion_cost = 1, int $replacement_cost = 1, int $deletion_cost = 1): int. The per-operation weights are a nice touch.

The catch

The function is not even the edit distance you usually want. You want Damerau-Levenshtein, which counts transposition, such as ab <-> ba as one edit, not two. Real typos are transpositions; bare Levenshtein punishes them twice. Also, older PHP versions refused strings longer than 255 bytes; PHP 8.0 removed that limit, so long inputs work now. Check execution time.

Modern replacements

For tasks that “match a user input against a dictionary”, the right answer is usually trigram for recall + Damerau-Levenshtein for ranking.

similar_text(), by Oliver, 1993

The algorithm

It recursively finds the longest common substring on both sides of the first match, count matching chars, return that count and, optionally, a percentage. The percentage is calculated with the formula: 2 * matches / (strlen($a) + strlen($b)) * 100.

The PHP function

similar_text(string $string1, string $string2, float &$percent = null): int. The by-reference &$percent parameter is an old PHP API style that we all just live with.

Reference: the PHP manual’s similar_text() page, which attributes the algorithm to Oliver (1993). It is a variant of Ratcliff/Obershelp pattern matching.

The catch

There are actually three problems stacked on top of each other. It’s O(N³) in the worst case. The percentage doesn’t match Levenshtein-derived similarity, so your unit tests against other tools won’t compare. And “longest common substring, recursively” is a strange definition of similarity: it’s basically a poor man’s diff.

Modern replacements

My experience is that if you’re calling similar_text() and the inputs are longer than 50 chars, you probably want a different tool entirely.

Future of these native functions

PHP is keeping them, and they are not deprecated by the engine. The manual still presents them as ordinary functions.

The actual modernization is happening off the standard engine:

  • ext-intl, which is bundled and links with the ICU library, gives transliteration, normalization, and collation. It doesn’t give Double Metaphone, but it gives the primitives to replace soundex().
  • FFI (PHP 7.4+) lets call into C and Rust libraries directly. If you need a faster Levenshtein than PHP’s, a native library such as rapidfuzz can be called this way.

PHP isn’t going to take these functions away, and it isn’t going to modernize them either. For the algorithms, the replacements are mostly Composer packages and extensions, and you have to pick the one that fits your data.

There are also a lot of algorithms that are not yet implemented off the shelf for PHP, either as pure-PHP code, or as a PHP extension or even an FFI extension. All of these are open opportunities.

When the text gets big: diff

All four legacy functions live in the same narrow band: short string, single score out. None of them handle well larger strings, and I mean, much larger ones. This is where you want to check these two articles that are 4,000 words each and mostly the same except for paragraphs 3 and 7.

When you cross that threshold, the algorithm you want isn’t a string metric: it’s a diff. Longest common subsequence at line level, optionally with word-level refinement. Reference: J. W. Hunt and M. D. McIlroy, An Algorithm for Differential File Comparison, 1976, the algorithm behind Unix diff; background on the underlying problem in Longest common subsequence, Wikipedia. Git’s diff, your IDE’s “compare files” view, the patch you can actually read.

PHP doesn’t ship a diff function. Reach for sebastian/diff, the PHPUnit ecosystem’s library. It gives you LCS-based line diffing and a renderer for inline or side-by-side output. Current releases require PHP 8.4+.

$differ = new \SebastianBergmann\Diff\Differ();
echo $differ->diff($old_text, $new_text);

There are also a lot of diff algorithms, depending on the level of energy you pour in searching for the difference, and the level of details you want to see.

PHP text comparisons

PHP’s text-comparison story covers a spectrum: byte identity at one end, with ===, line-level structural difference at the other, with diff. The four functions in the middle, soundex, metaphone, levenshtein, similar_text, are still available and still work for simple cases. For anything beyond that, the better tools are in Composer, PHP extensions, and they are worth the install.

Use the built-ins if they’re enough. Replace them when they aren’t. And when the input is big enough that none of them apply, you were never looking for a metric — you were looking for a diff.