开发者

Gettext placeholders

开发者 https://www.devze.com 2023-02-20 04:51 出处:网络
I am building a multilingual application in PHP + CodeIgniter. I have settled upon using gettext for UI text translation, and so far it has proven efficient and easy to work with.

I am building a multilingual application in PHP + CodeIgniter. I have settled upon using gettext for UI text translation, and so far it has proven efficient and easy to work with.

But now I am facing something really annoying: the gettext() function only accepts one parametre, while I'd like a printf-like behaviour that I get from Zend Framework's gettext adapter, where I can use %1$s, %2$s etc. as placeholders and then specify the replacement strings as additional parametres to Zend view's translate() function.

I do not wish to ditch gettext due to the easy translation management with .po files and poEdit (I can get it updated with a single click, after all). What are my options?

I have already tried 开发者_JS百科writing a helper to interact with gettext: run the first argument through gettext and then run strtr on the resulting string. Are there any other/better approaches you would recommend?


It's quite simple actually, you define a variadic function like this:

function myGettext($id)
{
    return vsprintf(gettext($id), array_slice(func_get_args(), 1));
}

Now doing myGettext('%u %s in a %s', 3, 'monkeys', 'tree') will return the expected string with the placeholders replaced by the remaining arguments. You obviously also need to implement a plural aware function that calls ngettext() instead.

Regarding poEdit, you have to modify the keywords it searches for, it's been a while since I last used it but it was quite simple, the only problem I faced was identifying keywords for plural support (see this).

Hope it helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号