Php declension function by case. Case declension module for PHP. API for word declination, getting gender (masculine, feminine), case, declension and other characteristics of a word

The morpher.so module is designed for case declension of words and phrases - surnames, first names and patronymics, names of cities and goods - in Russian and Ukrainian.

Declension function by cases

One million dollars goes tofromNaberezhnye Chelny" , " rod " ); ?> !

As a result we get:

One million dollars goes to Vasily Pupkin from Naberezhnye Chelny!

The morpher_inflect function inflects a phrase in the nominative case (first argument) into any case (second argument). The case can take the following meanings:

All strings passed to the library must be in UTF-8 encoding. The result is also returned in UTF-8.

Corresponding function for Ukrainian language called morpher_ukr_inflect . So far it only works with surnames, first names and patronymics and differs from Russian in the names of cases:

Translation into the plural has not yet been implemented in the Ukrainian version.

Function of breaking down a name into components

The morpher_split_fio function splits the input string into an array of last name, first name, middle name

F: Pupkin I: Vasily O:

Pluralization function

If you add the string "mn" to the second parameter, the result will be plural:

Remaining in stock 238 .

There are 238 pokers left in the warehouse.

If the first parameter is already plural, then the following will be returned:

#ERROR: Parameter 1 "text" is plural.

Genus Determination Function

" y " , " f " => " y " , " n " => " oh " , " p " => " y " ); $name = "experts"; $rod = morpher_get_gender ($name); echo "Respect". $endings [ $rod ] . " " . $name . " !\n " ; ?>

To determine the gender of surnames, first names and patronymics in Ukrainian, use the morpher_ukr_get_gender function. It only returns "m" (male) or "f" (female).

Function of writing numbers and monetary amounts

The morpher_spell function forms the spelling of the number and puts the given unit of measurement in the desired case:

calendar day" ); // 28 (Twenty eight) calendar days morpher_spell("1.2", "percentage"); // 1.2 (one point two) percent morpher_spell(2, "day"); // 2 (Two) days ?>

If you need to insert words into the text in a certain case, specify the case as the third parameter:

Duringcalendar day" , " R " ); ?> .

As a result, we get “Within 28 (Twenty-eight) calendar days.”

Acceptable case values: I, R, D, V, T, P and their analogues written in Latin, see. Preposition forms (predl-o and gde) are not supported in this function.

For the names of some monetary units, the morpher_spell function produces a spelling like this:

One hundred twenty-three rubles 45 kopecks morpher_spell(123.45, "USD"); // One hundred twenty-three US dollars 45 cents morpher_spell(123.45, "euro"); // One hundred twenty-three euros 45 cents?>

If desired, you can use abbreviated names of monetary units, with or without a dot:

One hundred twenty-three rubles. 45 kopecks morpher_spell(123.45, "$"); // One hundred twenty-three US dollars 45 cents morpher_spell (123.45, " UAH " ); // One hundred twenty-three UAH. 45 kopecks?>

Or three-letter currency codes of the international standard ISO 4217, such as RUB, USD, EUR, etc. In this case, the name of the country is automatically included in the name of the currency:

One hundred twenty-three Russian rubles 45 kopecks morpher_spell(123.45, "UAH"); // One hundred twenty-three Ukrainian hryvnia 45 kopecks morpher_spell(123.45, "KZT"); // One hundred twenty-three Kazakh tenge 45 tiyns?>

Error processing

If an error occurs, all library functions return a line starting with "#ERROR: " .

#ERROR: Parameter 1 "text" should not be empty.
#ERROR: Parameter 2 "case" should not be empty.
#ERROR: Parameter 1 "text" is not Russian.
#ERROR: Parameter 2 "case" is invalid.
#ERROR: Parameter 1 "text" is plural.

If you don't want the user to see these messages, check for the initial substring "#ERROR: " .

The morpher_inflect function expects 2 parameters, and morpher_get_gender - one. If called with the wrong number of parameters, the PHP interpreter issues a warning and continues executing the program.

Installing the module on Linux

For convenience and simplification of the installation procedure, the distribution includes a set of scripts that automate the installation of packages necessary for compilation, module assembly, and module registration as an extension for PHP. Considering big variety operating system distributions, various configuration options and features of building extensions for php, you need to understand that in some cases, when installing a module, there may be a need for additional actions that are not implemented by assembly scripts.

To start the automatic installation procedure, unpack the distribution into any directory, for example, morpher:

# mkdir morpher # cd morpher # tar xf ../morpher.tar # cd php

Run the build script with the command:

# bash build.sh

If successful, the morpher.so module file will be compiled and moved to the php extensions directory. The module will be registered in the php configuration, and the functionality of the module will be checked automatically using a test. The text output of the assembly script should contain a message indicating successful testing:

Running tests... ... done.

Your module is ready to use. The directory can now be deleted:

# rm -r morpher

If you have problems with the build, you need to make sure that all the necessary packages are installed and configured on your system. To assemble and operate the module you must install:

You can start just building the module without additional actions with the command:

# bash compile.sh

The finished file will be in the morpher/php/modules directory. It needs to be placed in the PHP extensions directory, for example:

# php-config --extension-dir/usr/lib/php5/20121212 # mv modules/morpher.so /usr/lib/php5/20121212/

The extension directory may be different on your system.

# bash setup.sh

or specify the extension name yourself in the php.ini file. You can check the functionality of the extension by manually running a test PHP script from the command line:

# php -f test.php Running tests... ... done.

Possible errors during assembly and ways to eliminate them

Error: /usr/bin/ld: cannot find -lm

Reason: You do not have the glibc-static package installed.

Error: .../include/php/php_config.h:2526:30: error: call of overloaded ‘isnan(double&)’ is ambiguous. (line number may differ in your PHP version and configuration)

JavaScript is blocked in your browser. Please enable JavaScript for the site to function!

API for word declination, getting gender (masculine, feminine), case, declension and other characteristics of a word

Word Declension API

Options:
inflect- a word or a list of words separated by a space. The following options available only if one word is transmitted.
partofspeech
DescriptorExampleDescription
CMothernoun
Predadjective
KR_APILbeautifulshort adjective
INFINITIVEgoinfinitive
Gcomingpersonal verb
Participlewalkingparticiple
PARTICIPLEgoingparticiple
KR_PARTICIPLEbuiltshort participle
NUMBEReightnumeral (quantitative)
NUMBER-Peighthordinal number
MSHepronoun-noun
MS-PREDCnothingpredicative pronoun
MS-Panypronominal adjective
NCooladverb
ANCESTORInterestingpredicate
PREFERunderpretext
UNIONAndunion
BETWEENOuchinterjection
FREQUENTwell, wouldparticle
INVODNCertainlyintroductory word
PHRAZfloundering bays, zgiphraseological unit
grammems– . Specified separated by "," (comma). To exclude, indicate "-" (minus) before the gramme.
GrammemaDescription
Genus
mrmasculine
zhrfeminine
Wedneuter gender
mr-zhrgeneral gender (orphan, drunkard)
Number
unitssingular
plplural
Case
themnominative
rdgenitive
dtdative
vnaccusative
TVinstrumental
etcprepositional
soundvocative (father, god)
2 second genitive or second prepositional case
Time
nstpresent time
willFuture tense
prshpast tense
Face
1lfirst person
2lsecond person
3lthird party
Animacy
odanimate
Butinanimate
View
St.perfect view
nsimperfect species
Transitivity
nptransition
neintransitive
Pledge
dstactive voice
pagepassive voice
Other
0 immutable
bezlimpersonal verb
pvlimperative mood (imperative)
attractionpossessive (not used)
prevsuperlative (for adjectives)
comparecomparative degree (for adjectives)
qualityqualitative adjective
Semantic features
Namename (Ivan, Mikhail)
femmesurname (Ivanov, Sidorov)
reportpatronymic (Ivanovich, Mikhailovich)
loktoponym (Moscow, Lena, Everest)
abbrabbreviation (KPSS, RONO)
orgorganization
questioninterrogative adverb
indicatedemonstrative adverb
slangjargon
decompositioncolloquial
archarchaism
HRHtypo
poetpoetic
profprofessionalism
info– display each form as an array with additional information

Http://site/service/api.php?inflect=Magadan&json

("0":"MAGADAN","1":"MAGADAN","2":"MAGADAN","3":"MAGADAN","4":"MAGADAN","5":"MAGADAN"," 6":"MAGADANY","7":"MAGADANA","8":"MAGADANA","9":"MAGADANA","limit":38)

Http://site/service/api.php?inflect=Magadan












Http://site/service/api.php?inflect=Rostov-on-Don&xml

<0>ROSTOV-ON-DON <1>ROSTOV-ON-DON <2>ROSTOV-ON-DON <3>ROSTOV-ON-DON <4>ROSTOV-ON-DON 46

To get all the inanimate plural adjectives from the word "wedding" call:

Https://site/service/api.php?inflect=wedding&json&partofspeech=P&grammems=NO,MN&info
Get:
("0":("word":"WEDDING","partofspeech":"P","grammems":["DT","QUALITY","MN","NO","OD"]), " 1":("word":"WEDDING","partofspeech":"P","grammems":["IM","QUALITY","MN","BUT","OD"]), "2" :("word":"WEDDING","partofspeech":"P","grammems":["VN","KACH","MN","BUT"]), "3":("word": "WEDDING","partofspeech":"P","grammems":["QUALITY","MN","BUT","OD","RD"]), "4":("word":"WEDDING ","partofspeech":"P","grammems":["QUALITY","MN","BUT","OD","PR"]), "5":("word":"WEDDING" "partofspeech":"P","grammems":["QUALITY","MN","NO","OD","TV"]) ,,"limit":19) Without the info parameter:
http://site/service/api.php?inflect=wedding&json&partofspeech=P&grammems=NO,MN
("0":"WEDDING","1":"WEDDING","2":"WEDDING","3":"WEDDING", "4":"WEDDING","5":"WEDDING"," limit":19)

API for getting word gender, name: male, female

API for getting gender: male, female by name. Using this API, you can get the user's gender using the username. This will eliminate the need to fill out an additional form during registration.

A very popular problem faced Web programmers, This Declension of words in PHP. For example, you need to display how many minutes ago a message was left. You can simply write a number and a word " minutes". But then it will be written very strangely, for example, " 1 minutes", "2 minutes" and so on. In fact, without Declension of words in PHP You can't do it unless, of course, you want to write in Russian.

The problem will seem very difficult to beginners, but, in fact, there is a certain pattern to the declension of words. See for yourself: " 1 minute, 2 minutes, 5 minutes, 11 minutes, 19 minutes, 21 minutes, 22 minutes, 25 minutes and so on"See a pattern? 1, 21, 31, 41 - always will be " minute". If the least significant digit is greater 1st and less 5 , while the number itself when divided by 100 has a remainder greater 20 (that is, for example, not a number 12 and not 112 ), then there will be " minutes". In other cases " minutes".

function getWord($number, $suffix) (
$keys = array(2, 0, 1, 1, 1, 2);
$mod = $number % 100;
$suffix_key = ($mod > 7 && $mod< 20) ? 2: $keys;
return $suffix[$suffix_key];
}
$array = array("minute", "minutes", "minutes"); $n = 21;

echo "$n $word
";
$n = 11;
$word = getWord($n, $array);
echo "$n $word
";
$n = 4;
$word = getWord($n, $array);
echo "$n $word
";
?>

By running this script you will see that Declension of words in PHP happens with a bang. I can only add that in addition to " minutes"there might be" day", "hour", "Human", "computer" and all other nouns that decline depending on the numeral.

Sandbox

Mr Olympia November 16, 2013 at 15:01

Full Name Declension - NameCaseLib PHP Framework

  • PHP

Hello, Habrahabr!

Today I will talk about a small but very useful framework - NameCaseLib.

I think many have encountered a situation where it was necessary to decline a person’s Last Name, First Name and Patronymic by case. This framework will help us get rid of numerous “bicycles”.

Installation

For NameCaseLib to work, we need PHP5 and the php_mbstring library to work with text in UTF-8 format.

Great, now all that remains is to connect the framework itself, for this we will download the necessary files.

NameCaseLib supports two languages: Russian and Ukrainian. The file NCL.NameCase.ru.php contains Russian declension rules, NCL.NameCase.ua.php, respectively, Ukrainian ones. The NCL folder contains the very “core” of the framework, that is, a set of basic functions.

So, let's create a file in .php format and check the functionality of this framework.

q("Maksimov Alexander Vasilievich"); # Output the resulting array. (Note: returns a simple indexable array) var_dump($array); ?>

Accordingly, in the same way, we can incline Ukrainian full names by connecting Ukrainian rules declination.

But let’s still look at what parameters the method contains q, and how else can it be used?

This method has 3 parameters, 2 of them can be omitted. The first parameter is the person’s full name, the second is the case (I will give a list of constants below; if the case is not specified (NULL), then the method returns all cases), and the third is the person’s gender. (The constants are also given below; if you do not specify the gender (NULL), the method will determine it itself)

Constants

To indicate gender, constants are used:
  • NCL::$MAN – male gender
  • NCL::$WOMAN – female

To indicate cases of the Russian language:

  • NCL::$IMENITLN - nominative case
  • NCL::$RODITLN - genitive case
  • NCL::$DATELN - dative case
  • NCL::$VINITELN - accusative case
  • NCL::$TVORITELN - instrumental case
  • NCL::$PREDLOGN - prepositional case

To indicate cases of the Ukrainian language:

  • NCL::$UaNazyvnyi – nameplate
  • NCL::$UaRodovyi – generic view
  • NCL::$UaDavalnyi – long-term admin
  • NCL::$UaZnahidnyi – famous video
  • NCL::$UaOrudnyi – weapon display
  • NCL::$UaMiszevyi – miscevyi vidminok
  • NCL::$UaKlychnyi – personal recognition

Notes

  1. The order of the name does not matter.
  2. It does not matter in which case the full name is indicated, after declension, the method returns the saved case of letters.

Definition of part of full name

Using the getFullNameFormat method, we can determine the part, or which parts of the full name we are using.

getFullNameFormat("Maksimov Alexander Vasilievich"); /* We get a format like: S F N, where: - S - Last name - N - First name - F - Middle name */ echo $fullName; ?>

But what should you do if the framework still cannot correctly determine how to decline your chosen name?

For this purpose, the library provides the qFullName method, which allows you to specify the Last Name, First Name, Patronymic and gender of a person in a certain sequence.

qFullName("Maksimov", "Alexander", "Vasilievich", NCL::$MAN, NCL::$TVORITELN, "S N F")."\n"; ?>

Results

NameCaseLib is a really user-friendly framework that includes many useful features. The site has complete documentation in Russian.

There is often a need inflect names in PHP. Agree that the phrase " Add as friend Ilya"sounds a lot worse than" Add Ilya as a friend". That's why Declension of names by case in PHP This is required quite often, and in this article I will tell you how you can implement this on your website.

I’ll say right away that ideal option, Unfortunately no. The first option is very obvious: find a database of names that will be in all cases, and add this table to yours. Then, by name in the nominative case, look for the corresponding case in the database. The disadvantages here are obvious: huge database, can’t cover all the names, extra load on the server.

The second option is to write your own class of name declensions in PHP, or use a ready-made one. Since the rules in the Russian language are quite complex, plus there are a lot of exceptions, therefore a very large library will be required, and even this is far from 100% the rescue. The most popular of all libraries dealing with Declension of names in PHP, is NameCaseLib .

After downloading this library and placing it on your website, you can use it like this:

Require_once "NCL.NameCase.ru.php"; // Connect the Russian library
$case = new NCLNameCaseRu(); // Create an object of the NCLNameCaseRu class
$array = $case->q("Rusakov Mikhail Yurievich"); // We get an array of 6 elements corresponding to 6 cases in which the input string will appear
print_r($array); // Output the array
?>

As you can see, using the library is very simple. On the other hand, my main advice will be the following: If possible, avoid the need to inflect words altogether.. All the same, sometimes people will introduce something that cannot be inclined in any way, and attempts to induce it will look ridiculous. It's not necessary to write " Add Ilya as a friend"It can be written simply" Add as Friend"on Ilya's page.