Created
August 11, 2015 14:02
-
-
Save pafnuty/de8e89506f78761f2830 to your computer and use it in GitHub Desktop.
Идентичные PHP и JS функции для правильного склонения слов
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Функция для склонения слов | |
* Пример использования: declination(5,'комментари|й|я|ев') | |
* | |
* @author Павел Белоусов <pb@info-expert.ru> | |
* | |
* @param int number число, для которого будет расчитано окончание | |
* @param string words слово и варианты окончаний для 1|2|1 (1 комментарий, 2 комментария, 100 комментариев) | |
* | |
* @return string - слово с правильным окончанием | |
*/ | |
function declination(number, words) { | |
"use strict"; | |
var w = words.split('|'), | |
n = Math.abs(number * 1); // abs на случай отрицательного значения | |
return n % 10 == 1 && n % 100 != 11 ? w[0] + w[1] : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? w[0] + w[2] : w[0] + w[3]); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
/** | |
* Функция для склонения слов | |
* Пример использования: declination(5,'комментари|й|я|ев') | |
* | |
* @author Павел Белоусов <pb@info-expert.ru> | |
* | |
* @param int n число, для которого будет расчитано окончание | |
* @param string words слово и варианты окончаний для 1|2|1 (1 комментарий, 2 комментария, 100 комментариев) | |
* | |
* @return string - слово с правильным окончанием | |
*/ | |
function declination($n = 0, $words) { | |
$words = explode('|', $words); | |
$n = abs((int)$n); // abs на случай отрицательного значения | |
return $n % 10 == 1 && $n % 100 != 11 ? $words[0] . $words[1] : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? $words[0] . $words[2] : $words[0] . $words[3]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment