plejus/pluralize

将任何英语单词变为复数形式。您还可以检查单词是否为复数或单数形式。

此包的官方仓库似乎已不存在,因此该包已被冻结。

1.0.0 2019-08-07 00:00 UTC

This package is auto-updated.

Last update: 2024-08-21 20:55:30 UTC


README

将任何英语单词变为复数或单数形式。您还可以检查单词是否为复数或单数形式。

模块包含不规则和不计数的规则列表。您还可以添加自定义规则。

安装

composer require plejus/pluralize

用法

<?php

use plejus\PhpPluralize\Inflector;

$inflector = new Inflector();

$output = $inflector->plural("dog");
// output: "dogs"

$output = $inflector->singular("dogs");
// output: "dog"

$output = $inflector->isPlural("dogs");
// output: true

$output = $inflector->isSingular("dogs");
// output: false

$inflector->addIrregularRule('something', 'some things');
$output = $inflector->plural("something");
// output: "some things"


$inflector->addSingularRule('/singles$/i', 'singular');
$output = $inflector->singular("singles");
// output: "singular

实际应用示例

将一些动物论坛标签分组以帮助用户找到内容

<?php

use plejus\PhpPluralize\Inflector;

$tags      = [
    100 => "dog",
    101 => "parrot",
    102 => "dogs",
    103 => "monkeys",
    104 => "cats",
    105 => "cat",
    106 => "doggies",
];

$inflector = new Inflector();
$inflector->addSingularRule('/doggies$/i', 'dog');

$groups = [];

foreach ($tags as $id => $tag) {
    $correctTag = $inflector->isSingular($tag)
        ? $tag
        : $inflector->singular($tag);

    if (!array_key_exists($correctTag, $groups)) {
        $groups[$correctTag] = [];
    }

    $groups[$correctTag][] = $id;
}

/*
 * Output:
 * 
 * Array
    (
        [dog] => Array
            (
                [0] => 100
                [1] => 102
                [2] => 106
            )
    
        [parrot] => Array
            (
                [0] => 101
            )
    
        [monkey] => Array
            (
                [0] => 103
            )
    
        [cat] => Array
            (
                [0] => 104
                [1] => 105
            )
    )
 */

显示单词的正确形式

<?php

use plejus\PhpPluralize\Inflector;

$inflector = new Inflector();

for ($i = 1; $i <= 3; $i++) {
    echo "I have $i " . $inflector->pluralize("apple", $i);
}

/*
*  Output:
*  "I have 1 apple"
*  "I have 2 apples"
*  "I have 3 apples"
*/

许可证

MIT