Posted By

brownrl on 06/27/11


Tagged

String language plural singular


Versions (?)

PHP dePlural


 / Published in: PHP
 

URL: http://www.itsgotto.be/cv.php

Small function to help de plural a word. Probably not up to the oxford english standard but close enough and extensible.

  1. <?php
  2.  
  3. // Function De-Plural
  4. //
  5. // Take a word that is pluraled and make it singular
  6. // helpful for transforming a string like "users" to "user"
  7. //
  8. // $word -> The word you want to de plural
  9. //
  10. // Please note that this function may or may not be the ultimate
  11. // oxford approved 100% catch all de pluralizer function but should
  12. // work for 90% I hope. Please comment if you have more rules to add.
  13. //
  14. function dePlural($word)
  15. {
  16.  
  17. $rules = array(
  18. 'ss' => false,
  19. 'os' => 'o',
  20. 'ies' => 'y',
  21. 'xes' => 'x',
  22. 'oes' => 'oe',
  23. 'ies' => 'y',
  24. 'ves' => 'fe',
  25. 's' => '',
  26. 'eet' => 'oot'
  27. // if you know more add them here
  28. );
  29.  
  30.  
  31. foreach( $rules as $key => $v )
  32. {
  33. // does the word end in a rule?
  34. if( preg_match( "/".$key."$/" , $word ) )
  35. {
  36. // we met that ss rule
  37. if($key === false)
  38. {
  39. return $word;
  40. }
  41. // return the word depluraled
  42. return preg_replace( "/".$key."$/" , $v , $word );
  43. }
  44. }
  45.  
  46. // ok we didn't find any rules so return the original word, sorry.... :(
  47. return $word;
  48. }
  49.  
  50.  
  51. // testing code probably not what you want to copy.
  52. $tests[] = "rabbitts";
  53. $tests[] = "Zebras";
  54. $tests[] = "Toes"; // this is a breaker O well!
  55. $tests[] = "vegetables";
  56. $tests[] = "cities";
  57. $tests[] = "ex-wives";
  58. $tests[] = "sexes";
  59. $tests[] = "feet";
  60.  
  61. foreach( $tests as $w )
  62. {
  63. echo dePlural( $w ) . "<br />\n";
  64. }
  65.  
  66.  
  67.  
  68.  
  69. ?>

Report this snippet  

You need to login to post a comment.