Fairy tales      04.02.2020

Php case declension. API for declension of words, obtaining gender (male, female), case, declension and other characteristics of a word. Definition of part of full name

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 write just a number and the word " minutes". But then it will be written very strangely, for example, " 1 minutes", "2 minutes"and so on. In fact, without word declension in PHP You can not do without, of course, if you want to write in Russian.

The problem will seem very difficult to beginners, but, in fact, the declension of words has a certain pattern. See for yourself: " 1 minute, 2 minutes, 5 minutes, 11 minutes, 19 minutes, 21 minutes, 22 minutes, 25 minutes and so on". See the pattern? 1, 21, 31, 41 - always will be " minute". If the least significant digit is greater than 1st and less 5 , while the number itself when divided by 100 has more remainder 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
";
?>

When you run 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 may be" day", "hour", "Human", "computer" and all other nouns that decline depending on the numeral.

JavaScript is blocked in your browser. Allow JavaScript for this site to work!

API for declining words, getting gender (male, female), case, declension and other characteristics of a word

Declension API

Options:
affect- a word or a list of words separated by a space. The following options are available only if a single word is passed.
partofspeech
DescriptorExampleDescription
CMothernoun
Predadjective
CR_APPbeautifulshort adjective
INFINITIVEgoinfinitive
Ggoesverb in personal form
GENERAL PARTICIPLEgoinggerund
PARTICIPLEgoingparticiple
CR_PARTICIPLEbuiltshort communion
NUMBEReightnumeral (quantitative)
NUMBER-Peighthordinal number
MSHepronoun-noun
MS-PRECnothingpredicative pronoun
MS-Panypronominal adjective
HCooladverb
ancestorInterestingpredicative
PROPOSEDunderpretext
UNIONAndunion
INTERNATIONALOuchinterjection
FREQUENTsame, wouldparticle
INTRODUCTIONCertainlyintroductory word
Phrasebays-flounders, zgiphraseological unit
grammes– . Specified with "," (comma). To exclude, precede the gramme with "-" (minus)
grammemeDescription
Genus
mrmasculine
fatfeminine
Wedneuter gender
mr-zhrcommon gender (orphan, drunkard)
Number
unitssingular
plplural
case
themnominative
rdgenitive
dtdative
extaccusative
tvinstrumental
etcprepositional
svvocative (father, god)
2 second genitive or second prepositional
Time
nstpresent time
budFuture tense
prshpast tense
Face
1lfirst person
2lsecond person
3lthird party
Animation
oneanimated
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 degree (for adjectives)
comparecomparative degree (for adjectives)
qualityquality adjective
Semantic features
Namename (Ivan, Mikhail)
famsurname (Ivanov, Sidorov)
otchpatronymic (Ivanovich, Mikhailovich)
loktoponym (Moscow, Lena, Everest)
abbrabbreviation (KPSS, RONO)
orgorganization
questioninterrogative adverb
indicatedemonstrative adverb
slangjargon
unfoldcolloquial
archarchaism
opctypo
poetpoetic
profprofessionalism
info- output each form as an array with additional information

Http://website/service/api.php?inflect=magadan&json

("0":"MAGADAN","1":"MAGADAN","2":"MAGADAN","3":"MAGADAN","4":"MAGADAN","5":"MAGADAN", " 6":"MAGADANOV","7":"MAGADANAM","8":"MAGADANAM","9":"MAGADANAH","limit":38)

Http://website/service/api.php?inflect=magadan












Http://website/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 from the word "wedding" all inanimate adjectives in plural call:

https://website/service/api.php?inflect=wedding&json&partofspeech=p&grammems=NO,MN&info
Get:
("0":("word":"WEDDING","partofspeech":"P","grammems":["DT","QUAL","MN","BUT","OD"]), " 1":("word":"WEDDING","partofspeech":"P","grammems":["IM","KACH","MN","BUT","OD"]), "2" :("word":"WEDDING","partofspeech":"P","grammems":["VN","KACH","MN","BUT"]), "3":("word": "WEDDING","partofspeech":"P","grammems":["QUAL","MN","BUT","OD","RD"]), "4":("word":"WEDDING ","partofspeech":"P","grammems":["QUAL","MN","BUT","OD","PR"]), "5":("word":"WEDDING", "partofspeech":"P","grammems":["QUAL","MN","BUT","OD","TV"]) ,"limit":19) Without parameter info:
http://website/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 the gender of a word, name: male, female

API for getting gender: male, female by name. With the help of this API, by username, you can get his gender. This will eliminate the need to fill in additional time during registration.

Often there is a need inflect names in PHP. Agree that the phrase Add as friend Ilya"sounds much worse than" Add Ilya as a friend". That's why case declension in PHP is required quite often, and in this article I will tell you how you can implement it on your site.

I must say right away that there is no ideal option, alas. The first option is very obvious: find a database of names that will be in all cases, and add this table to yourself. Then, by name in the nominative case, look for the corresponding case in the base. The downsides are obvious: huge database, do not cover all the names, extra load on the server.

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

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

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

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

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

Case declension function

One million dollars goesfromNaberezhnye 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 on the following meanings:

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

Corresponding function for Ukrainian language called morpher_ukr_inflect . It works so far only with surnames, names and patronymics and differs from Russian in case names:

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

The function of breaking down the full name into components

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

F : Pupkin I : Vasily O :

Plural translation function

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

Remaining in stock 238 .

There are 238 pokers left in stock.

If the first parameter is already plural, then it will return:

#ERROR: Parameter 1 "text" is plural.

Genus function

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

The morpher_ukr_get_gender function is used to determine the gender of last names, first names and patronymics in Ukrainian. It only returns "m" (male) or "f" (female).

The function of writing numbers and amounts of money

The morpher_spell function forms a number spelling and puts the given unit of measure in the correct 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 the spelling needs to be inserted into the text in a specific case, specify the case as the third parameter:

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

As a result, we get "Within 28 (twenty-eight) calendar days."

Valid 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, "US dollar"); // 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 the abbreviated names of monetary units, with or without a dot:

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

Or three-letter codes of currencies 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

When an error occurs, all library functions return a string 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, while morpher_get_gender expects one. When called with the wrong number of parameters, the PHP interpreter issues a warning and continues the program.

Installing a module on Linux

For convenience and simplification of the installation procedure, the distribution kit includes a set of scripts that automate the installation of packages necessary for compilation, module assembly and module registration as a PHP extension. Given the wide variety of operating system distributions, various options configuration and features of building extensions for php, you need to understand that in some cases, when installing a module, it may be necessary to perform additional actions that are not implemented by build 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 with a test. The text output of the build script should contain a message about 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 build and run the module, you need to install:

You can only start building the module without any additional steps 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)

Sandbox

mr olympia November 16, 2013 at 03:01 pm

Name Declension - NameCaseLib PHP Framework

  • PHP

Hello Habrahabr!

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

I think many have come across a situation where it was necessary to decline the Surname, Name and Patronymic of a person in cases. 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 it remains 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 “core” of the framework itself, that is, a set of basic functions.

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

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

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

But, let's still analyze 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 full name of the person, the second is the case (I will list the constants below; if the case (NULL) is not specified, the method returns all cases), and the third is the gender of the person. (Constants are also listed below; if you do not specify a gender (NULL), the method will determine it itself)

Constants

The following constants are used to indicate gender:
  • NCL::$MAN - male gender
  • NCL::$WOMAN - female

To indicate the cases of the Russian language:

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

To indicate the cases of the Ukrainian language:

  • NCL::$UaNazyvnyi – naming name
  • NCL::$UaRodovyi
  • NCL::$UaDavalnyi
  • NCL::$UaZnahidnyi
  • NCL::$UaOrudnyi
  • NCL::$UaMiszevyi
  • NCL::$UaKlychnyi - nickname

Notes

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

Definition of part of full name

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

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

But, what to do if, nevertheless, the framework cannot correctly determine how to decline the name you have chosen?

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

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

Results

NameCaseLib is a really handy framework that includes many useful features. The site has full documentation in Russian.