Doctrine Inflector
repository·2.1.x·Indexed 11 days ago
https://github.com/doctrine/inflectorA lightweight PHP library for linguistic string manipulations, including changing word casing and converting between singular and plural forms. It supports multiple languages such as English, French, Italian, and Spanish, and provides methods like tableize(), classify(), camelize(), pluralize(), and singularize().
What's inside Doctrine Inflector
- Doctrine Inflector is a PHP library designed for string manipulations. It specifically provides tools to handle uppercase/lowercase transformations and to manage singular and plural forms of words.
Initialize an Inflector using InflectorFactory
2.1.xThe recommended way to create an
Inflectorinstance is through theDoctrine\ eflector\InflectorFactoryclass. By default, the factory creates an English inflector.use Doctrine\Inflector\InflectorFactory; $inflector = InflectorFactory::create()->build();Install Doctrine Inflector via Composer
2.1.xTo use Doctrine Inflector in your project, install it using Composer:
$ composer require doctrine/inflectorEnglish language inflection rules in Inflectible
2.1.xThe
Doctrine\Inflector\Rules\English\Inflectibleclass provides the core rules for English language inflection. It defines how words are transformed between singular and plural forms using three types of rules:- Singular Transformations: Rules applied to convert a plural word to its singular form using regex patterns.
- Plural Transformations: Rules applied to convert a singular word to its plural form using regex patterns.
- Irregular Substitutions: Direct mappings for words that do not follow standard pattern-based rules (e.g.,
man->men).
While these methods are primarily used internally by the Inflector engine to build its rule sets, they represent the authoritative definition of English inflection logic within the library.
Configure custom singular and plural rules
2.1.xYou can define custom inflection rules (transformations, patterns, and substitutions) using the
InflectorFactorybefore building the instance. This allows for fine-grained control over how words are transformed.use Doctrine\Inflector\InflectorFactory; use Doctrine\Inflector\Rules\Pattern; use Doctrine\Inflector\Rules\Patterns; use Doctrine\Inflector\Rules\Ruleset; use Doctrine\Inflector\Rules\Substitution; use Doctrine\Inflector\Rules\Substitutions; use Doctrine\Inflector\Rules\Transformation; use Doctrine\Inflector\Rules\Transformations; use Doctrine\Inflector\Rules\Word; $inflector = InflectorFactory::create() ->withSingularRules( new Ruleset( new Transformations( new Transformation(new Pattern('/^(bil)er$/i'), '\1'), new Transformation(new Pattern('/^(inflec|contribu)tors$/i'), '\1ta') ), new Patterns(new Pattern('singulars')), new Substitutions(new Substitution(new Word('spins'), new Word('spinor'))) ) ) ->withPluralRules( new Ruleset( new Transformations( new Transformation(new Pattern('^(bil)er$'), '\1'), new Transformation(new Pattern('^(inflec|contribu)tors$'), '\1ta') ), new Patterns(new Pattern('noflect'), new Pattern('abtuse')), new Substitutions( new Substitution(new Word('amaze'), new Word('amazable')), new Substitution(new Word('phone'), new Word('phonezes')) ) ) ) ->build();How RulesetInflector handles multiple rulesets
2.1.xThe
RulesetInflectorimplements theWordInflectorinterface and allows you to combine multipleRulesetobjects. When inflecting a word, it follows a specific priority order across the provided rulesets:- Uninflected Check: For each ruleset, it first checks if the word matches any uninflected word patterns. If it matches, the word is returned immediately without further inflection.
- Irregular Inflection: If no uninflected pattern matches, it attempts to apply the ruleset's irregular inflection rules. The first ruleset that produces a result different from the original word wins.
- Regular Inflection: If no irregular inflection is applied, it attempts to apply the ruleset's regular inflection rules. The first ruleset that produces a result different from the original word wins.
- Fallback: If no rulesets produce a change, the original word is returned as-is.
This allows you to layer language rules (e.g., applying English rules first, then falling back to a more generic ruleset).
// Example of composing multiple rulesets $inflector = new RulesetInflector($englishRuleset, $genericRuleset); $result = $inflector->inflect('word');Create an Inflector for a specific language
2.1.xTo use a language other than English, use the
createForLanguage()method on the factory with a constant from theDoctrine\Inflector\Languageclass.Supported languages include:
Language::ENGLISHLanguage::ESPERANTOLanguage::FRENCHLanguage::ITALIANLanguage::NORWEGIAN_BOKMALLanguage::PORTUGUESELanguage::SPANISHLanguage::TURKISH
use Doctrine\Inflector\InflectorFactory; use Doctrine\Inflector\Language; $inflector = InflectorFactory::createForLanguage(Language::SPANISH)->build();Transform text with Inflector methods
2.1.xThe
Inflectorclass provides several methods for text transformation:tableize($string): ConvertsModelNametomodel_name.classify($string): Convertsmodel_nametoModelName.camelize($string): Convertsmodel_nametomodelName(usesclassifythen lowercases the first character).capitalize($string, $delimiters = ' '): Capitalizes all words. Unlike PHP'sucwords, you can specify custom delimiters.pluralize($string): Returns the plural form of a word.singularize($string): Returns the singular form of a word.urlize($string): Generates a URL-friendly string (e.g.,my-first-blog-post).unaccent($string): Removes accents from a string (e.g.,añobecomesano).
Manually construct an Inflector
2.1.xIf you prefer not to use the factory, you can manually instantiate the
Inflectorby providing a singular and a plural word inflector. This typically involves usingCachedWordInflectorandRulesetInflectorwith specific language rules.use Doctrine\Inflector\Inflector; use Doctrine\Inflector\CachedWordInflector; use Doctrine\Inflector\RulesetInflector; use Doctrine\Inflector\Rules\English; $inflector = new Inflector( new CachedWordInflector(new RulesetInflector( English\Rules::getSingularRuleset() )), new CachedWordInflector(new RulesetInflector( English\Rules::getPluralRuleset() )) );Use a No-operation (Noop) inflector
2.1.xIf you need an inflector that performs no changes (returning the input as output), use
Doctrine\Inflector\NoopWordInflector. This is useful for implementing the Null Object pattern.use Doctrine\Inflector\Inflector; use Doctrine\Inflector\NoopWordInflector; $inflector = new Inflector(new NoopWordInflector(), new NoopWordInflector());Get English singular transformations
2.1.xThe
getSingular()method returns an iterable ofTransformationobjects used to derive singular forms from plural words in English. Each transformation uses aPattern(regex) and a replacement string.// Returns Transformation[] Doctrine\Inflector\Rules\English\Inflectible::getSingular();RulesetInflector class
2.1.xThe
RulesetInflectorclass is used to perform word inflection by iterating through a collection ofRulesetobjects. It implements theWordInflectorinterface.Constructor
public function __construct(Ruleset $ruleset, Ruleset ...$rulesets)Requires at least oneRulesetobject. SubsequentRulesetobjects are appended to the internal list and processed in the order they are provided.Methods
public function inflect(string $word): stringInflects the given string based on the prioritized rulesets. Returns an empty string if the input is empty.use Doctrine\Inflector\RulesetInflector; use Doctrine\Inflector\Rules\Ruleset; // Assuming $ruleset is an instance of Ruleset $inflector = new RulesetInflector($ruleset); $inflectedWord = $inflector->inflect('some_word');