Сайты должны говорить по-русски!

В давние времена, когда я начал изучать строение world wide web и мучал мозг великолепным изобретением программистов студии Лебедева Parser 3, на их форуме был найден класс для работы с числительными, позже я переписал этот алгоритм на PHP для использования с MODx.

Итак, код (в варианте PHx модификатора):

<?php
/**
 * num_decline
 * This formats correct russian word construstions, example:
 *       $time_text = " $hours ";
 *       $time_text .= num_decline($hours,"час","часа","часов");
 * Usage as phx:
 *       [\+template.variable:numdecline=`день,дня,дней`+\]
 **/
if (!function_exists('num_decline')) {
function num_decline($num,$nominative,$genitive_singular,$genitive_plural) {

// последнее число из строки вида xxx/yyy/zzz
if(strpos($num,"/")) {
  $pos = strrpos($num, "/");
  $num = substr($num, $pos+1);
}
    if($num > 10 and ((floor( ($num % 100) / 10) ) == 1)){
        $result = $genitive_plural;
        }
    else {
        switch($num % 10){
            case 1: $result = $nominative; break;
            case 2: $result = $genitive_singular; break;
            case 3: $result = $genitive_singular; break;
            case 4: $result = $genitive_singular; break;
            case 5: $result = $genitive_plural; break;
            case 6: $result = $genitive_plural; break;
            case 7: $result = $genitive_plural; break;
            case 8: $result = $genitive_plural; break;
            case 9: $result = $genitive_plural; break;
            case 0: $result = $genitive_plural; break;
            }
    }
    return $result;
}
} // end if !function...

$num = isset($num) ? $num : 0;
$arr = explode(",", $options);
$nominative = isset($arr[0]) ? $arr[0] : '';
$genitive_singular = isset($arr[1]) ? $arr[1] : '';
$genitive_plural = isset($arr[2]) ? $arr[2] : '';

return num_decline($output, $nominative,$genitive_singular,$genitive_plural);
?>

Для использования необходимо создать сниппет с именем phx:numdecline и скопировать в него код. После этого в чанке с цифровыми переменными (текущего времени, к примеру) обрабатывать их конструкцией [\+hour+\] [\+hour:numdecline=`час,часа,часов`+\] [\+minutes+\] [\+minutes:numdecline=`минута,минуты,минут`+\] (слеши - не нужны, это я ленивый ;)

В результате на Вашем сайте никогда не встретятся конструкции типа «11 часов 23 минут» или «41 попугая».

Давайте строить правильный web!

«Русский язык» — это хорошо!

Write a comment

  • Required fields are marked with *.

If you have trouble reading the code, click on the code itself to generate a new random code.
 
Segr
Posts: 1
Comment
Немного попроще...
Reply #1 on : Sat February 07, 2009, 22:14:38
<?php
$titles = explode('|', $options);
$__case = (int)$output;
if ($__case<=0) $__case=0;
if ($__case==0) {
$return = isset($titles[3])?$titles[3]:'';
} else {
$__cases = array (2, 0, 1, 1, 1, 2, 2, 2, 2, 2);
if ($__case%100 > 10 && $__case%100 < 20) $__case = 2;
else $__case = $__cases[$__case%10];
$return = $titles[$__case];
}
return str_replace('?', $output, $return);
?>