Text mit variabler Anzahl an Platzhaltern mittels Zend_Translate übersetzenTranslate text based on variable number of placeholders using Zend_Translate

In case you are wondering how to quickly translate text using Zend_Translate and variable numbers of placeholders here is a quick solution that uses built-in PHP funtionality: vsprintf to the rescue!

First setup Zend_Translate to your needs, e.g. in Bootstrap:

protected function _initTranslations() {
  $translate = new Zend_Translate(array(
    'adapter' => 'gettext',
    'content' => APPLICATION_PATH . DIRECTORY_SEPARATOR . 'languages',
    'scan' => Zend_Translate::LOCALE_DIRECTORY,
    'tag' => 'YourProject_Translation',
    'disableNotices' => true));

  Zend_Registry::set('Zend_Translate', $translate);

This configuration uses a gettext to parse translation files. Then in order to translate text with placeholders simply use vsprintf after the actual translation has been done by Zend_Translate to substitute any placeholders with their actual values:

echo vsprintf(Zend_Registry::get('Zend_Translate')
  ->translate('Your message with 2 placeholders: The %s and the %s.'), 
  array('first', 'second'));

Which will produce “Your message with 2 placeholders: The first and the second.”

You may also like...

2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.