【问题标题】:gettext of string with number带数字的字符串的gettext
【发布时间】:2012-06-30 08:26:27
【问题描述】:

我想使用 gettext 翻译一个句子并保持原样,就像在这些例子中一样:

"i am 100 years old" -> Tengo 100 años de edad (spanish)
"i am 10 years old"   -> Tengo 10 años de edad (spanish)

"i slept 24 hours a day" ->  Ich schlief 24 Stunden am Tag (german)
"i slept 4 hours a day" ->   Ich schlief 4 Stunden am Tag (german)

我猜字符串应该是这样的:'i slept #24# hours a day' 但我不确定...

有没有什么方法可以翻译字符串而不考虑其中的具体数字(可能是某种格式)?

【问题讨论】:

  • 您可以使用preg_match 获取号码。这是它的正则表达式!\d+!
  • 获取数字并不能解决问题并提供一个很好的解决方案。我想保存所有组合的输入翻译:“我每天睡 24 小时”,“我每天睡 23 小时” " , "我一天睡 22 小时" , "我一天睡 21 小时" ....
  • 如果我认为这是解决方案,我不会评论它。我刚刚“提出”了一个想法。
  • 节省输入所有选项的时间,只更改数字是我想避免的。

标签: php text numbers gettext


【解决方案1】:

您所说的问题很容易解决:

$translation = gettext("I am %d years old");
$phrase      = sprintf($translation, $n);

但实际上还有另一个问题。在某些语言中,数字后面的名词(在您的示例中为“年”)根据使用的数字而不同。而且它不仅仅是单/复数形式:例如,在俄语中

"I am 10 years old" = "Мне 10 лет"
"I am 21 years old" = "Мне 21 год"

对于这些类型的翻译,您应该使用更高级的ngettext() 函数,如下所示:

setlocale(LC_ALL, 'cs_CZ');
printf(ngettext("%d window", "%d windows", 1), 1); // 1 okno
printf(ngettext("%d window", "%d windows", 2), 2); // 2 okna
printf(ngettext("%d window", "%d windows", 5), 5); // 5 oken

是的,数字本身被使用了两次:第一次在ngettext 中获取正确的名词形式,然后在printf 中填写占位符。

【讨论】:

    【解决方案2】:

    如果你总是知道格式,sscanf 可以帮助你。

    sscanf('i am %d years old', $years);
    $newString = sprintf('Tengo %d años de edad', $years);
    

    【讨论】:

      【解决方案3】:

      您可以在翻译后使用替换数字。

      str_replace('#NUM#', $num,  gettext('i slept #NUM# hours a day'));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-18
        • 2010-11-23
        • 1970-01-01
        • 2018-01-23
        • 2013-10-29
        • 2014-01-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多