Skip to content

47: Move Phonetic Matching Out of Core

Isolate a phonetic encoder behind a callable so you can replace the deprecated metaphone() implementation and verify your search behavior.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable metaphone-migration.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/47-metaphone-migration/metaphone-migration.php
metaphone-migration.php
<?php
declare(strict_types=1);
function groupNames(array $names, callable $encode): array
{
$groups = [];
foreach ($names as $name) {
$groups[$encode($name)][] = $name;
}
return $groups;
}
$names = ['Smith', 'Smyth', 'Jones'];
echo json_encode(groupNames($names, soundex(...)), JSON_THROW_ON_ERROR), PHP_EOL;
{"S530":["Smith","Smyth"],"J520":["Jones"]}

Persisted phonetic keys depend on the chosen algorithm, its input normalization, and its version. The demo uses the built-in English-oriented soundex() to show the callable boundary. Choose your userland encoder with representative fixtures before generating replacement search keys.

Add two spelling variants from your own dataset. Record whether each algorithm groups them together and keep the result as a migration fixture.

Continue with Replace Deprecated MySQLi Charset and Statement Calls.