iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😎

[PHP] Converting Japanese Voiced and Semi-voiced Marks from NFD to NFC

に公開
2024/07/16

In NFD format, voiced and semi-voiced sounds are represented by a combination of a base character and a combining character. The combining characters used for voiced and semi-voiced marks are U+3099 and U+309A, respectively.

<?php

echo "は\u{3099}", PHP_EOL;
echo "は\u{309A}", PHP_EOL;

In macOS, creating files with Japanese names in Finder results in NFD.

Before the introduction of APFS (Apple File System) to macOS in 2017, Apple's proprietary NFD (commonly known as Apple modified NFD) was used for file names on macOS.

To convert a string from NFD format to NFC format, use normalizer_normalize.

<?php

var_dump(
  "ば" === normalizer_normalize("は\u{3099}"),
  "ぱ" === normalizer_normalize("は\u{309A}")
);

When using normalizer_normalize, care must be taken to avoid converting unrelated characters such as old-form Kanji. Characters that should be excluded from conversion are called "Composition Exclusion Characters".

<?php

var_dump(
  "神" === normalizer_normalize("神", Normalizer::FORM_C),
  "神" === normalizer_normalize("神", Normalizer::FORM_D)
);

In order to avoid involving Composition Exclusion Characters in the Unicode normalization process, it is necessary to filter them using regular expressions or an API that can handle grapheme clusters.

First, let's try using regular expressions. A combination of Hiragana or Katakana with a voiced or semi-voiced mark can be represented by Unicode properties as [\p{Hiragana}\p{Katakana}][\x{3099}\x{309A}]. Since it is difficult to keep remembering the code points for voiced and semi-voiced marks, they can be expressed as [\p{Hiragana}\p{Katakana}]\p{Mn} by replacing them with the Mn property (Non-spacing mark, a character used to modify other characters).

Therefore, you can write it as follows using preg_replace_callback or mb_ereg_replace_callback.

$str = "は\u{3099}は\u{3099}とハ\u{309A}ハ\u{309A}と神";

$ret = 'ばばとパパと神';
var_dump(
    $ret === dakuon_normalize($str),
    $ret === dakuon_normalize2($str)
);

function dakuon_normalize(string $str): string {
    return preg_replace_callback(
        '/[\p{Hiragana}\p{Katakana}]\p{Mn}/su',
        fn($matches) => normalizer_normalize($matches[0]),
        $str);
}

function dakuon_normalize2(string $str): string {
     return mb_ereg_replace_callback(
         '[\p{Hiragana}\p{Katakana}]\p{Mn}',
         fn($matches) => normalizer_normalize($matches[0]),
         $str);
}

Next, let's try extracting grapheme clusters. After extracting a grapheme cluster, Unicode normalization is applied if it consists of two code points and the second code point is 0x3099 or 0x309A.

$str = "は\u{3099}は\u{3099}とハ\u{309A}ハ\u{309A}と神";
$ret = 'ばばとパパと神';
var_dump(
    $ret === dakuon_normalize3($str)
);

function dakuon_normalize3(string $str): string {

    $size = grapheme_strlen($str);
    $ret = '';

    for ($i = 0; $i < $size; ++$i) {
        $g = grapheme_substr($str, $i, 1);

        if (2 === mb_strlen($g)) {
            $cp = mb_ord(mb_substr($g, 1, 1));

            if ($cp == 0x3099 || $cp == 0x309A) {
                $g = normalizer_normalize($g);
            }
        }

        $ret .= $g;
    }

    return $ret;
}

Another method is to simply replace the characters using str_replace.

<?php

$str = "ハ\u{309A}ハ\u{309A}と神";
var_dump("パパと神" === dakuon_normalize4($str));

function dakuon_normalize4(string $str): string {
  $before = [
    'が', 'ぎ', 'ぐ', 'げ', 'ご',
    'ざ','じ', 'ず', 'ぜ', 'ぞ',
    'だ', 'ぢ', 'づ', 'で', 'ど',
    'ば', 'び', 'ぶ', 'べ', 'ぼ',
    'ぱ', 'ぴ', 'ぷ', 'ぺ', 'ぽ',
    'ガ', 'ギ', 'グ', 'ゲ', 'ゴ',
    'ザ', 'ジ', 'ズ', 'ゼ', 'ゾ',
    'ダ', 'ヂ', 'ヅ', 'デ', 'ド',
    'バ', 'ビ', 'ブ', 'ベ', 'ボ',
    'パ', 'ピ', 'プ', 'ペ', 'ポ',
    'ヴ'
  ];

  $after = [
    'が', 'ぎ', 'ぐ', 'げ', 'ご',
    'ざ', 'じ', 'ず', 'ぜ', 'ぞ',
    'だ', 'ぢ', 'づ', 'で', 'ど',
    'ば', 'び', 'ぶ', 'べ', 'ぼ',
    'ぱ', 'ぴ', 'ぷ', 'ぺ', 'ぽ',
    'ガ', 'ギ', 'グ', 'ゲ', 'ゴ',
    'ザ', 'ジ', 'ズ', 'ゼ', 'ゾ',
    'ダ', 'ヂ', 'ヅ', 'デ', 'ド',
    'バ', 'ビ', 'ブ', 'ベ', 'ボ',
    'パ', 'ピ', 'プ', 'ペ', 'ポ',
    'ヴ'
  ];

  return str_replace($before, $after, $str);
}

Taking a benchmark shows that str_replace is faster.

php test.php

array(2) {
  ["normalizer"]=>
  int(523097868)
  ["str_replace"]=>
  int(199818621)
}
test.php
$str = "ハ\u{309A}ハ\u{309A}と神";

var_dump(benchmark([
  'normalizer' => function() use ($str) { dakuon_normalize3($str); },
  'str_replace' => function() use ($str) { dakuon_normalize4($str); }
]));

function benchmark(array $callables, int $repeat = 100000): array {

    $ret = [];
    $save = $repeat;

    foreach ($callables as $key => $callable) {

        $start = hrtime(true);

        do {
            $callable();
        } while($repeat -= 1);

        $stop = hrtime(true);
        $ret[$key] = $stop - $start;
        $repeat = $save;
    }

    return $ret;
}

Discussion