Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP soundex() and metaphone() functions

Reference for PHP soundex() and metaphone(): phonetic keys for English words, how to match names that sound alike, their limits and a Levenshtein comparison.

soundex() and metaphone() turn an English word into a short key that describes how it sounds. Two words with the same key probably sound alike, even if they are spelled differently. This helps with name searches where users do not know the spelling.

soundex() always returns a four-character code: a letter followed by three digits. metaphone() returns a variable-length string of consonant sounds and is generally more accurate for English.

PHP
<?php
echo soundex("Robert"), " ", soundex("Rupert");  // R163 R163

Try it

PHP Phonetic keys

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.

PHP Finding names that sound alike

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.

Syntax

PHP
soundex(string $string): string
metaphone(string $string, int $max_phonemes = 0): string
Name Description
$string The word to encode. Non-letters are ignored.
$max_phonemes metaphone() only. The maximum length of the result; 0 means no limit.

Return value: the phonetic key as a string.

Errors: metaphone() throws a ValueError if $max_phonemes is negative.

Usage notes

  • English only. Both algorithms assume English pronunciation; results for other languages are unreliable.
  • Soundex keeps the first letter, so "Catherine" and "Katherine" get different codes even though they sound the same. metaphone() handles that case.
  • Keys are lossy. Different words can share a key (false positives), and similar sounds can get different keys (false negatives). Use them to narrow candidates, not to decide.
  • Store the key in a database column to search by sound with an indexed equality check.
  • Compare keys with ===, or measure closeness with levenshtein() on the keys.
  • Letters only: digits, spaces and punctuation are dropped; accented characters are not understood.