Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 147 ยท Strings in Depth

Comparing Strings - Equality, Similarity and Sounds-Like

Compare PHP strings by order, natural order, edit distance and pronunciation with strcmp, strnatcmp, similar_text, levenshtein, soundex and metaphone, plus a "did you mean" example.

Most of the time you compare two strings with === and you are done: they are identical or they are not. But real programs often need a softer question. Which of two names sorts first? Is img10.png after img9.png? Did the visitor mean install when they typed instal? Does "Smith" sound like "Smyth"? PHP ships a small family of functions for each of those questions, and knowing which one to pick saves you from writing your own.

This lesson walks through four ideas: ordering comparisons (strcmp and friends), natural ordering, similarity (similar_text, levenshtein) and phonetics (soundex, metaphone). It ends with a "did you mean" helper that combines them. For equality of secrets such as tokens, never use these functions; use hash_equals() as explained in Cryptography.

Ordering: strcmp and its relatives

strcmp($a, $b) compares two strings byte by byte and returns a negative number, zero or a positive number. Since PHP 8.2 the result is always exactly -1, 0 or 1; older versions returned the byte difference. Never depend on the exact magnitude, only on the sign.

Variants exist for the cases you meet most:

Function Difference
strcasecmp() ignores case (ASCII letters only)
strncmp() compares only the first n bytes
strncasecmp() first n bytes, ignoring case
strcoll() uses the current locale's collation rules
substr_compare() compares a slice of one string with another, optionally ignoring case
PHP strcmp family

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

substr_compare() is the tidy way to write "starts with" and "ends with" checks that ignore case, although PHP 8 also gives you str_starts_with() and str_ends_with() for the case-sensitive version. These functions work on bytes, so for accented or non-Latin text you should normalize and compare with the mb_* tools from Multibyte Strings.

== is not a safe replacement for strcmp(). Two numeric-looking strings are compared as numbers, so "10" == "1e1" is true, while strcmp("10", "1e1") correctly says they differ. See Comparison Operators and Type Juggling.

Natural ordering: strnatcmp

Plain strcmp() sorts img12.png before img2.png, because the character 1 comes before 2. People expect the number inside the text to count as a number. strnatcmp() (and the case-insensitive strnatcasecmp()) implements that "natural order". It plugs straight into the sorting functions.

PHP Natural order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

natsort() and natcasesort() do the same job in place and preserve keys, while sort($a, SORT_NATURAL | SORT_FLAG_CASE) gives you the flag form.

How similar are two strings?

similar_text

similar_text($a, $b, &$percent) returns the number of matching characters found by repeatedly taking the longest common substring, and writes a similarity percentage into the third argument. The result depends on the order of the arguments, so treat it as a rough score.

levenshtein

The Levenshtein distance is the minimum number of single-character edits (insert, replace, delete) needed to turn one string into the other. levenshtein("kitten", "sitting") is 3: replace k with s, replace e with i, insert g. A distance of 0 means the strings are equal. You can weight the operations with three optional costs (insertion, replacement, deletion).

Since PHP 8.0 there is no 255-byte limit on the arguments, but the work grows with the product of the two lengths, so do not run it over long documents.

PHP similar_text and levenshtein

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Use levenshtein() when you care about typos (one wrong or missing key), and similar_text() when you want a percentage to show people. Both are case-sensitive and byte-based: lowercase the input first with mb_strtolower() for user-facing matching.

Does it sound the same?

soundex() returns a four-character code (a letter plus three digits) built from how an English word sounds. Names that sound alike get the same code. metaphone() produces a variable-length phonetic key and is usually more accurate for English words.

PHP Sounds like

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both functions are designed for English and ignore anything that is not a basic Latin letter. Treat the result as a hint for search ("people with a similar surname"), not as proof of a match. For serious fuzzy search use a search engine, or the database features covered in Databases.

Example: a "did you mean" helper

A command-line tool or router can offer a suggestion when the user mistypes. Compare the input against every known name with levenshtein(), keep the smallest distance and only suggest it if it is small enough.

PHP Did you mean...?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The threshold matters: a distance of 2 is fine for words of 6+ letters, but too generous for a three-letter command. A common refinement is max(1, intdiv(strlen($input), 3)).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does levenshtein("kitten", "sitting") return?

    Two replacements (k to s, e to i) and one insertion (g) make three single-character edits.
  2. 2. Which function sorts img2.png before img10.png?

    strnatcmp() compares the digit runs as numbers, so 2 comes before 10. strcmp() compares byte by byte and puts 10 first.
  3. 3. Why should you not rely on the exact value returned by strcmp()?

    Older PHP versions returned byte differences and PHP 8.2 normalized to -1, 0 and 1. Code that checks only the sign is correct on every version.
  4. 4. Which statement about soundex() and metaphone() is true?

    Both build phonetic keys from English spelling rules, so use them for fuzzy "sounds like" search only.

Summary

  • strcmp() and friends order strings by bytes; use strcasecmp(), strncmp() and substr_compare() for case-insensitive or partial checks.
  • strnatcmp(), strnatcasecmp() and natsort() treat digits as numbers ("natural order").
  • levenshtein() counts edits; similar_text() gives matching characters and a percentage.
  • soundex() and metaphone() make English sounds-like keys.
  • Combine levenshtein() with a threshold to build "did you mean" suggestions.
  • Never use these functions to compare secrets; use hash_equals().

Next: Multibyte Strings