dongwei1954 2014-10-19 09:29
浏览 34

Gettext不同的翻译

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.

  • 写回答

1条回答 默认 最新

  • donglian2106 2014-10-19 13:12
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口