Using the Symfony string component to get the singular or plural of a word

Published on 2022-10-15 • Modified on 2022-10-15

This snippet shows how to use the Symfony string component to get the singular or plural of a word. It isn't easy to do this as there are many special cases. Note that these functions return an array of results, not a string, as it may have more than one result (depending on different contexts). The inflector is also available in French.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\String\Inflector\EnglishInflector;
use Symfony\Component\String\Inflector\FrenchInflector;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet223Trait
{
    public function snippet223(): void
    {
        // English
        $inflector = new EnglishInflector();
        $result = $inflector->pluralize('tooth');
        print_r($result);
        $result = $inflector->singularize('leaves');
        print_r($result);

        // French
        $inflector = new FrenchInflector();
        $result = $inflector->pluralize('hibou');
        print_r($result);
        $result = $inflector->singularize('chevaux');
        print_r($result);

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!