How to translate a string containing multiple plurals?

523 views Asked by At

I want to translate a script that lists the content of a folder. There's a summary of included files, folders and the total size displayed. So far I translated all strings using gettext, but I'm stuck here and look for an elegant way to solve translating a string that might contain multiple plurals. Probably needless to mention, but since each language is different, I want to avoid concatenate strings.

$summary = sprintf(_('%1$s folders and %2$s files, %3$s %4$s in total'), $total_folders, $total_files, $total_size, $unit);

Possible states (0-cases are left out intentionally):

  • 1 folder and 1 file, 100 kilobytes in total
  • 1 folder and 2 files, 200 kilobytes in total
  • 2 folders and 1 file, 100 kilobytes in total
  • 2 folders and 2 files, 200 kilobytes in total

I think ngettext() would be the appropriate replacement for _(), but combining that with my example is getting over my head.

2

There are 2 answers

0
Nek On

The pluralization is a basical problem with translations. Here is an example of implementations that can probably help you: http://symfony.com/doc/current/components/translation/usage.html#pluralization

Maybe you should consider to take the translation component they did for symfony.

1
Deep On

I have solution. But, maybe you don't known - many languages have three forms of plural.

function plural($n, $f1, $f3, $f5)
{
    return $n%10==1&&$n%100!=11?$f1:($n%10>=2&&$n%10<=4&&($n%100<10||$n%100>=20)?$f3:$f5);
}
// for english
echo plural($x, 'monkey', 'monkeys', 'monkeys');