Create a gist now

Instantly share code, notes, and snippets.

Embed
The reason for this snippet, is to have gettext always combined with sprintf in a easy accessible way.
<?php
/*************
* 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
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment