For those who use and like gettext for localization.
This is a snippet to have a simpler and more powerful way to access it over PHP default.
It automatically uses sprintf when needed, and you don’t have to write a big ass line for a simple plural translation.
Code is also in the Gist
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
/************* * gettext aliases * Singular, Plural integrated with sprintf * http://andrecatita.com **********************/ function _t() { $args = func_get_args(); $num = func_num_args(); $args[0] = gettext($args[0]); if ($num <= 1) return $args[0]; return call_user_func_array('sprintf', $args); } function __t() { $args = func_get_args(); $args[0] = ngettext($args[0], $args[1], $args[2]); array_splice($args, 1, 1); return call_user_func_array('sprintf', $args); } // How to use // _t for singular echo _t('You are a dog'); // Outputs: You are a dog echo _t('You are a %s', 'horse'); // Outputs: You are a horse // __t for plural echo __t('I have eaten %d %s', 'I have eaten %d %ss', 1, 'apple'); // Outputs: I have eaten 1 apple echo __t('I have eaten %d %s', 'I have eaten %d %ss', 2, 'apple'); // Outputs: I have eaten 2 apples echo __t('I killed %d human', 'I killed %d humans - %d %s', '1', '9', 'were assholes'); // Outputs: I killed 1 human (remaining parameters are ignored) echo __t('I killed %d human', 'I killed %d humans - %d %s', '10', '9', 'were assholes'); // Outputs: I killed 10 humans - 9 were assholes |
0 Comments to "PHP gettext localization alias with sprintf"