简体   繁体   中英

Gettext Different Translation

I have a problem with gettext in PHP. Think of a situation where a word or expression in the source language can have different meanings.

For example: Word A word has two meanings; one is B and one is C . In a part of website we should use B . And in another part we should use C .

When we write _('A') How can ve get B or C ? There should be a solid way to handle this.

Gettext supports so-called message contexts . PHP doesn't have a native method for this, but it can easily be implemented .

Assuming we want to use the term “amount” in different contexts – in one context, it means “the count of a set of items”, in anonther context, it refers to “invoice amount”.

It works in several steps:

First: Instead of using the gettext() function, you would use a custom one; let's call it contextGettext() .

echo contextGettext('amount', 'count of items');
echo contextGettext('amount', 'invoice amount');

This method looks like this:

function contextGettext($string, $context)
{
    // http://www.php.net/manual/de/book.gettext.php#89975
    $contextString = "{$context}\004{$string}";
    $translation = gettext($contextString);
    return ($translation === $contextString) ? $string : $translation;
}

Note the \\004 : This is the separator which delimits the context identifier from the message string, as per gettext specification. (Nothing you need to really care about, just to know the background.)

When collecting translatable strings with the xgettext tool, you would add the following --keyword argument for the context-sensitive strings:

xgettext … --keyword="contextGettext:2c,1" …

Your .po file will then have the following entries:

msgctxt "count of items"
msgid "amount"
msgstr ""

msgctxt "invoice amount"
msgid "amount"
msgstr ""

After translating the catalog, generating the .mo files and restarting your webserver, your web application will output the correct strings in the correct place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM