如果您事先知道字符串中可能包含哪些单词,则可以执行以下操作:
// 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);
总的来说,如果您只需要 4 个特定的场合,那就需要做很多准备工作。但如果你经常使用它,我希望这会有所帮助。