Posted By

Scooter on 03/14/09


Tagged


Versions (?)

Soundex


 / Published in: PHP
 

URL: http://reusablecode.blogspot.com/2009/03/soundex.html

Convert individual characters or entire strings to their soundex equivalents.

  1. <?php
  2. /*
  3.   Copyright (c) 2009, reusablecode.blogspot.com; some rights reserved.
  4.  
  5.   This work is licensed under the Creative Commons Attribution License. To view
  6.   a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or
  7.   send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California
  8.   94305, USA.
  9.   */
  10.  
  11. // http://en.wikipedia.org/wiki/Soundex
  12.  
  13. // Calculate soundex code for entire strings, and soundex digits for individual characters.
  14. function soundex($someString)
  15. {
  16. // Rather than write a separate function to convert consonants to digits, I decided to overload the soundex function.
  17. if (str_len($someString) == 1)
  18. {
  19. // Calculate soundex digit for an individual character.
  20. switch (strtolower($someString))
  21. {
  22. case "b":
  23. case "f":
  24. case "p":
  25. case "v":
  26. return "1";
  27. break;
  28. case "c":
  29. case "g":
  30. case "j":
  31. case "k":
  32. case "q":
  33. case "s":
  34. case "x":
  35. case "z":
  36. return "2";
  37. break;
  38. case "d":
  39. case "t":
  40. return "3";
  41. break;
  42. case "l":
  43. return "4";
  44. break;
  45. case "m":
  46. case "n":
  47. return "5";
  48. break;
  49. case "r":
  50. return "6";
  51. default:
  52. // Remove vowels right away instead of during a later step.
  53. return "";
  54. }
  55. }
  56. else
  57. {
  58. // Calculate soundex code for an entire string.
  59.  
  60. // The first letter remains intact.
  61. $result = strtoupper(substr($someString, 0, 1));
  62.  
  63. // Replace consonants with digits and remove vowels.
  64. for ($i = 2; $i <= str_len($someString); $i++)
  65. {
  66. $result .= soundex(substr($someString, $i, 1));
  67. }
  68.  
  69. // Collapse adjacent identical digits into a single digit of that value.
  70. for ($i = 1; $i <= 6; $i++)
  71. {
  72. while (substr_count($result, $i . $i) != 0)
  73. {
  74. $result = str_replace($i . $i, $i, $result);
  75. }
  76. }
  77.  
  78. // Return the starting letter and the first three remaining digits.
  79. // If needed, append zeroes to make it a letter and three digits.
  80. return str_pad(substr($result, 0, 4), 4, "0", STR_PAD_RIGHT);
  81. }
  82. }
  83. ?>

Report this snippet  

You need to login to post a comment.