B-Teck!

お仕事からゲームまで幅広く

​【PHP】英単語を複数形にする

変換ルール

  • 不規則変化の名詞は辞書を持ち、対応する単語に変換する
  • 不規則変化の辞書に単語が存在しない場合、以下の優先順位で単語を変換する
    1 . 末尾が「s、sh、ch、o、x」の場合は「es」をつける
    2 . 末尾が「f、fe」の場合は「ves」に置き換える
    3 . 末尾二文字が「母音 + y」の場合は「s」をつける
    4 . 3でマッチングしたもの以外で末尾が「y」の場合は「ies」に置き換える
    5 . 1~4でマッチングしなかったものの末尾に「s」を付ける

ソースコード

不規則変化する名詞は調べるのがだるかったのでいくつか抜粋。
実際使うときはある程度網羅したものを用意するべし。

<?php
function toPlural($in){
    // 不規則変化する名詞については配列に持つ(抜粋)
    // 作りこむ場合はしっかり辞書を用意しよう
    $dic = [
        "dictionary" => "dictionaries",
        "fox" => "foxes",
        "dish" => "dishes",
        "watch" => "watches",
        "gentleman" => "gentlemen",
        "leaf" => "leaves",
        "radio" => "radios",
        "class" => "classes",
        "knife" => "knives",
        "foot" => "feet"
    ];
    
    // 不規則変化の辞書に存在する場合は優先して変換
    if (array_key_exists($in, $dic)) {
        return $dic[$in];
    } else {
        $tmpStr = $in;
        
        // 規則のある文字を置換
        // 1. 末尾が「s、sh、ch、o、x」の場合は「es」をつける
        $tmpStr = preg_replace("/(s|sh|ch|o|x)$/","$1es",$tmpStr);
        
        // 2. 末尾が「f、fe」の場合は「ves」に置き換える
        $tmpStr = preg_replace("/(f|fe)$/","ves",$tmpStr);
        
        // 3. 末尾二文字が「母音 + y」の場合は「s」をつける
        $tmpStr = preg_replace("/(a|i|u|e|o)y$/","$1ys",$tmpStr);
        
        // 4. 3でマッチングしたもの以外で末尾が「y」の場合は「ies」に置き換える
        $tmpStr = preg_replace("/y$/","ies",$tmpStr);
        
        // 5. マッチングしなかったものの末尾に「s」を付ける
        if (!preg_match("/s$/",$tmpStr)) {
            $tmpStr = $tmpStr."s";
        }
        
        return $tmpStr;
    }
}

// テストコード
$test[] = "axis";
$test[] = "baby";
$test[] = "book";
$test[] = "box";
$test[] = "boy";
$test[] = "bus";
$test[] = "cat";
$test[] = "church";
$test[] = "class";
$test[] = "dictionary";
$test[] = "dish";
$test[] = "dog";
$test[] = "foot";
$test[] = "fox";
$test[] = "gentleman";
$test[] = "hero";
$test[] = "judge";
$test[] = "knife";
$test[] = "lady";
$test[] = "leaf";
$test[] = "photo";
$test[] = "pig";
$test[] = "play";
$test[] = "potato";
$test[] = "radio";
$test[] = "study";
$test[] = "toy";
$test[] = "video";
$test[] = "watch";


foreach($test as $value){
    echo toPlural($value)."\n";
}