1

I have the following phrase and want to translate it.

$lifeTime = 'Expires in '.$days.($days == 1 ? ' day ':' days ' ).$h.(($h == 1 ? ' hour ':' hours ' ));

My question is: will I need to split the phrase, translate separated and concatenate them ? Is there a way to __n() function accept multiple "instances" of singular/plural with their respective counts on a single phrase ?

A bit confusing. A example to make it clear:

__('I have %s eggs and %s milk boxes', $eggs, $milk)

This will not have singular and plural form. Can I make it translate the entire phrase without having to split it in two __n() function calls ?

Matheus Vellone
  • 79
  • 1
  • 2
  • 8

1 Answers1

0

If you know beforehand what words might come in your strings you could do as follows:

// the preperation/setup
$translations = Array();
$translations['hours']['search'] = "%hour";
$translations['hours']['inflections'] = Array("hour", "hours");

$translations['milk']['search'] = "%milk";
$translations['milk']['inflections'] = Array("milk bottle", "bottles of milk");
// add what else you might need

function replaceWithPlurals($heystack, $translations) {
  foreach ($translations as $key => $vals) {
    $heystack = str_replace($vals['search'], $vals['cnt']." ".$vals['inflections'][usePlural($vals['cnt'])], $heystack);      
  }
  return $heystack;
}

function usePlural($cnt) {
  if($cnt==1) return 0;
  else return 1;
}


// dynamic vars
$heystack = "I drank %milk in %hour";
$hours = 1;
$milk = 2;
$translations['hours']['cnt'] = $hours;
$translations['milk']['cnt'] = $milk;

// the actual usage
echo replaceWithPlurals($heystack, $translations);

overall that's quite a lot of preperation if you would only need that for 4 specific occations. But if you regular use it I hope that will help.

Jeff
  • 6,895
  • 1
  • 15
  • 33
  • I guess this will work, but this way, the translations will be via code. Since I'm using i18n translations with .po files, i was curious if was possible do this in the i18n way. – Matheus Vellone May 02 '15 at 01:05