New in Symfony 4.3: Better inflector

Symfony includes an internal component called Inflector whose responsibility is to transform English words from plural to singular. It's used in the PropertyInfo and PropertyAccess components to find the singular form of a property name:

1
2
3
4
use Symfony\Component\Inflector\Inflector;

$result = Inflector::singularize('teeth');  // tooth
$result = Inflector::singularize('radii');  // radius

In Symfony 4.3 we've improved the component in several ways. First, we've removed its @internal tag, so this component is no longer considered internal and you can make your projects depend on it thanks to the Symfony BC promise.

Second, we've turned it into a full Inflector thanks to the new pluralize() method, which returns the plural form of the given singular English word:

1
2
3
4
5
6
use Symfony\Component\Inflector\Inflector;

$result = Inflector::pluralize('bacterium');  // bacteria
$result = Inflector::pluralize('alumnus');    // alumni
$result = Inflector::pluralize('news');       // news
$result = Inflector::pluralize('GrandChild'); // GrandChildren

Sometimes it's not possible to determine a unique singular/plural form for the given word. In those cases, the methods return an array with all the possible forms:

1
2
3
4
5
use Symfony\Component\Inflector\Inflector;

Inflector::singularize('leaves');  // ['leaf', 'leave', 'leaff']

Inflector::pluralize('person');    // ['persons', 'people']

Read the Inflector component documentation.

Comments

Awesome! Thanks!
Nice one.
It's awsome! Thanks

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.