## Posted By

Scooter on 03/14/09

# Soundex

/ Published in: PHP

Convert individual characters or entire strings to their soundex equivalents.

`<?php    /*    Copyright (c) 2009, reusablecode.blogspot.com; some rights reserved.        This work is licensed under the Creative Commons Attribution License. To view    a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or    send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California    94305, USA.    */     // http://en.wikipedia.org/wiki/Soundex     // Calculate soundex code for entire strings, and soundex digits for individual characters.    function soundex(\$someString)    {        // Rather than write a separate function to convert consonants to digits, I decided to overload the soundex function.        if (str_len(\$someString) == 1)        {            // Calculate soundex digit for an individual character.            switch (strtolower(\$someString))            {                case "b":                case "f":                case "p":                case "v":                    return "1";                    break;                case "c":                case "g":                case "j":                case "k":                case "q":                case "s":                case "x":                case "z":                    return "2";                    break;                case "d":                case "t":                    return "3";                    break;                case "l":                    return "4";                    break;                case "m":                case "n":                    return "5";                    break;                case "r":                    return "6";                default:                    // Remove vowels right away instead of during a later step.                    return "";            }        }        else        {            // Calculate soundex code for an entire string.             // The first letter remains intact.            \$result = strtoupper(substr(\$someString, 0, 1));             // Replace consonants with digits and remove vowels.            for (\$i = 2; \$i <= str_len(\$someString); \$i++)            {                \$result .= soundex(substr(\$someString, \$i, 1));            }             // Collapse adjacent identical digits into a single digit of that value.            for (\$i = 1; \$i <= 6; \$i++)            {                while (substr_count(\$result, \$i . \$i) != 0)                {                    \$result = str_replace(\$i . \$i, \$i, \$result);                }            }             // Return the starting letter and the first three remaining digits.            // If needed, append zeroes to make it a letter and three digits.            return str_pad(substr(\$result, 0, 4), 4, "0", STR_PAD_RIGHT);        }    }?>`