Created
September 30, 2016 19:03
-
-
Save zzap/b33facbf38815f5cb3fab261ed0aea7c to your computer and use it in GitHub Desktop.
Properly pluralize string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Define irregular plurals | |
* | |
* @return array Array of irregular plurals | |
*/ | |
function zzap_irregular_plurals() { | |
$irregulars = array( | |
'man' => 'men', | |
'woman' => 'women', | |
'fungus' => 'fungi', | |
'thief' => 'thieves', | |
'medium' => 'media', | |
'person' => 'people', | |
'echo' => 'echoes', | |
'hero' => 'heroes', | |
'potato' => 'potatoes', | |
'veto' => 'vetoes', | |
'auto' => 'autos', | |
'memo' => 'memos', | |
'pimento' => 'pimentos', | |
'pro' => 'pros', | |
'knife' => 'knives', | |
'leaf' => 'leaves', | |
'bus' => 'busses', | |
'child' => 'children', | |
'quiz' => 'quizzes', | |
# words whose singular and plural forms are the same | |
'equipment' => 'equipment', | |
'fish' => 'fish', | |
'information' => 'information', | |
'money' => 'money', | |
'moose' => 'moose', | |
'news' => 'news', | |
'rice' => 'rice', | |
'series' => 'series', | |
'sheep' => 'sheep', | |
'species' => 'species' | |
); | |
// filter if needed | |
return apply_filters( 'zzap_irregular_plurals', $irregulars ); | |
} | |
/** | |
* Pluralize string | |
* | |
* Check if string is irregular and, relevant to its ending, | |
* create plural form. | |
* | |
* @param string $string Singular that needs to be pluralized | |
* @return string Returns pluralized sting | |
*/ | |
function zzap_pluralize( $string ) { | |
// get array with irregulars | |
$irregulars = zzap_irregular_plurals(); | |
// endings that get 'es' in plural | |
$es = array( 's', 'z', 'ch', 'sh', 'x' ); | |
// get the last letter from string | |
$last_letter = substr( $string, -1 ); | |
// string found in irregulars, apply plural from irregulars array | |
if ( array_key_exists( $string, $irregulars ) ) : | |
return $irregulars[$string]; | |
// strings ending with 'y' | |
elseif ( $last_letter == 'y' ) : | |
// if last two characters are 'ey' replace both with 'ies' | |
if ( substr( $string, -2 ) == 'ey' ) : | |
return substr_replace( $string, 'ies', -2, 2 ); | |
// otherwise replace just last one | |
else : | |
return substr_replace( $string, 'ies', -1, 1 ); | |
endif; // substr( $string, -2 ) == 'ey' | |
// string's end match 'es' array, add that 'es' | |
elseif ( in_array( substr( $string, -2 ), $es ) || in_array( substr( $string, -1 ), $es ) ) : | |
return $string . 'es'; | |
// any other case | |
else : | |
return $string . 's'; | |
endif; // array_key_exists( $string, $irregulars ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment