---
title: "Modernizing PHP’s String-Comparison Functions"
url: https://www.exakat.io/modernizing-phps-string-comparison-functions/
date: 2026-11-20
modified: 2026-11-20
lang: en
author: "dams"
description: "Modernizing 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..."
categories:
  - "Technology"
tags:
  - "feature"
  - "fuzzy"
  - "native PHP"
  - "php"
  - "string"
image: https://www.exakat.io/wp-content/uploads/2026/11/stone-wall.640.jpg
word_count: 2098
---

# Modernizing PHP’s String-Comparison Functions

# Modernizing 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)](https://patents.google.com/patent/US1261167A/en), [NARA Soundex coding guide](https://www.archives.gov/research/census/soundex), [Soundex, Wikipedia](https://en.wikipedia.org/wiki/Soundex).

### 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

- **Double Metaphone**, by Lawrence Philips, 2000, the actual successor. It returns a primary and an alternate code, hence the name: it knows that one spelling can have two plausible pronunciations. Composer offers [`noodlesnz/double-metaphone`](https://packagist.org/packages/noodlesnz/double-metaphone), a pure PHP, a port of Philips's algorithm, last released 2016. For a faster, native option, [`iliaal/phonetic`](https://packagist.org/packages/iliaal/phonetic) is a C extension covering Double Metaphone, Beider-Morse, Daitch-Mokotoff, and more; it needs PHP 8.1+ and is installed with `pie install iliaal/phonetic`. Reference: Lawrence Philips, *The Double Metaphone Search Algorithm*, C/C++ Users Journal, June 2000, summarised in the [NIST Dictionary of Algorithms and Data Structures](https://xlinux.nist.gov/dads/HTML/doubleMetaphone.html).
- **Beider-Morse Phonetic Matching**, the language-aware, returns a set of candidate encodings. It is the gold standard for genealogy. Composer has [`zendevio/bmpm`](https://packagist.org/packages/zendevio/bmpm), for PHP 8.4+ and [`sbrendtro/bmpm`](https://packagist.org/packages/sbrendtro/bmpm), older, object-oriented interface. The native [`iliaal/phonetic`](https://packagist.org/packages/iliaal/phonetic) extension also covers it. Reference: [Beider-Morse Phonetic Matching](https://iijg.org/beider-morse/) and the [BMPM page of Stephen P. Morse](https://stevemorse.org/phonetics/bmpm.htm).
- **Daitch-Mokotoff Soundex**, for Slavic/Yiddish/Jewish names, where Russell Soundex is openly bad. Composer offers [`zendevio/bmpm`](https://packagist.org/packages/zendevio/bmpm). [`dautkom/bmdm`](https://packagist.org/packages/dautkom/bmdm), from 2016 is the older, widely used option. [`iliaal/phonetic`](https://packagist.org/packages/iliaal/phonetic) also includes it. Reference: [JewishGen Soundex page](https://www.jewishgen.org/infofiles/soundex.html).
- **Kölner Phonetik** is the equivalent for German. Composer has it with [`hollodotme/cologne-phonetic`](https://packagist.org/packages/hollodotme/cologne-phonetic), which requires PHP 5.5+ and `ext-iconv`. Reference: [Kölner Phonetik, German Wikipedia](https://de.wikipedia.org/wiki/K%C3%B6lner_Phonetik).

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 `k`in `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](https://en.wikipedia.org/wiki/Metaphone) 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](https://caversham.otago.ac.nz/) and [Caverphone, Wikipedia](https://en.wikipedia.org/wiki/Caverphone).

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](https://en.wikipedia.org/wiki/Levenshtein_distance).

### 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

- **Damerau-Levenshtein**, the transposition-aware. Composer has it with [`oefenweb/damerau-levenshtein`](https://packagist.org/packages/oefenweb/damerau-levenshtein), since PHP 7.1+ and last released 2022, and [`edgaras/strsim`](https://packagist.org/packages/edgaras/strsim), since PHP 8.2+, actively maintained. The latter also covers Jaro-Winkler and Levenshtein. Reference: Fred J. Damerau, [*A technique for computer detection and correction of spelling errors*, CACM 1964](https://doi.org/10.1145/363958.363994), and [Damerau–Levenshtein distance, Wikipedia](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance).
- **Jaro / Jaro-Winkler**, designed for short human names. It rewards common prefixes. This is what deduplication and record-linkage systems actually use. Composer offers [`edgaras/strsim`](https://packagist.org/packages/edgaras/strsim) and [`webd/language`](https://packagist.org/packages/webd/language). Reference: [Jaro–Winkler distance, Wikipedia](https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance).
- **Levenshtein automaton + trie**. This one is for questions such as "all dictionary words within `k`edits". It is vastly faster than brute force. I could not find a Composer package that implements a Levenshtein automaton: this one is up for grabs. For dictionary-scale correction, [`jakhotiya/symspell-php`](https://packagist.org/packages/jakhotiya/symspell-php) uses the Symmetric Delete algorithm, a different approach with the same goal. Reference for the automaton: Klaus Schulz and Stoyan Mihov, [*Fast string correction with Levenshtein automata*, 2002](https://doi.org/10.1007/s10032-002-0082-8), and [Levenshtein automaton, Wikipedia](https://en.wikipedia.org/wiki/Levenshtein_automaton). Reference for SymSpell: [the SymSpell repository](https://github.com/wolfgarbe/SymSpell).
- **BK-tree / vantage-point tree**. This index structure exploits the metric property of edit distance to prune the search. It is usually implemented in your own code or in your search engine. Nice to know, and without PHP specific implementation. Reference: Burkhard and Keller, [*Some approaches to best-match file searching*, CACM 1973](https://doi.org/10.1145/362003.362025), and [BK-tree, Wikipedia](https://en.wikipedia.org/wiki/BK-tree).
- **Trigram (q-gram) indexing**: it is the same trick [Postgres `pg_trgm`](https://www.postgresql.org/docs/current/pgtrgm.html) uses, so let the database do it. It is quite efficient.

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](https://www.php.net/manual/en/function.similar-text.php), which attributes the algorithm to Oliver (1993). It is a variant of [Ratcliff/Obershelp pattern matching](https://en.wikipedia.org/wiki/Gestalt_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

- **Normalized Damerau-Levenshtein**: `1 - dist / max(len)`. It is faster, more intuitive, and it gives you the same 0 to 1 "how similar?" UX without a surprise. Use Composer and [`oefenweb/damerau-levenshtein`](https://packagist.org/packages/oefenweb/damerau-levenshtein) or [`edgaras/strsim`](https://packagist.org/packages/edgaras/strsim) for the distance.
- **Jaccard / Sørensen-Dice over n-grams**: this one is fast, indexable, the standard for typo detection and "did you mean...?". Easy to write yourself in a few lines. Reference: [Jaccard index, Wikipedia](https://en.wikipedia.org/wiki/Jaccard_index) and [Sørensen–Dice coefficient, Wikipedia](https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient).
- **Monge-Elkan** algorithm, for record linkage: pairwise field similarity across tokens. Reference: Alvaro E. Monge and Charles P. Elkan, [*The field matching problem: Algorithms and applications*, KDD 1996](https://pubs.dbs.uni-leipzig.de/dc/node/753).
- **Smith-Waterman** algorithm. This is what fuzzy substring match actually looks like when done right. Reference: Smith and Waterman, [*Identification of common molecular subsequences*, J. Mol. Biol. 1981](https://doi.org/10.1016/0022-2836%2881%2990087-5).

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](https://www.php.net/manual/en/book.intl.php)**, 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](https://www.php.net/manual/en/book.ffi.php)** (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](https://github.com/rapidfuzz/rapidfuzz-cpp) 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](https://www.cs.dartmouth.edu/%7Edoug/diff.pdf), the algorithm behind Unix `diff`; background on the underlying problem in [Longest common subsequence, Wikipedia](https://en.wikipedia.org/wiki/Longest_common_subsequence). 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`](https://packagist.org/packages/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.