Skip to content

Commit

Permalink
feat: 取首字母时,能否保留完整的英文 #199
Browse files Browse the repository at this point in the history
  • Loading branch information
overtrue committed Mar 19, 2024
1 parent 7e23ee5 commit 8255ee3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Pinyin.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,18 @@ public static function nameAbbr(string $string): Collection
return self::abbr($string, true);
}

public static function abbr(string $string, bool $asName = false): Collection
public static function abbr(string $string, bool $asName = false, bool $preserveEnglishWords = false): Collection
{
return self::noTone()
->noPunctuation()
->when($asName, fn ($c) => $c->surname())
->convert($string)
->map(function ($pinyin) {
->map(function ($pinyin) use ($string, $preserveEnglishWords) {
// 如果内容在原字符串中,则直接返回
if ($preserveEnglishWords && str_contains($string, $pinyin)) {
return $pinyin;
}

// 常用于电影名称入库索引处理,例如:《晚娘2012》-> WN2012
return \is_numeric($pinyin) || preg_match('/\d{2,}/', $pinyin) ? $pinyin : \mb_substr($pinyin, 0, 1);
});
Expand Down
5 changes: 5 additions & 0 deletions tests/PinyinTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ public function test_abbr()

$this->assertPinyin(['d', 'f', 's', 'c', 'd', 'z', 'z', '123', 'r'], Pinyin::abbr('Ⅲ度房室传导阻滞123人'));
$this->assertPinyin(['d', 't', 'f'], Pinyin::abbr('单田芳'));

// https://github.com/overtrue/pinyin/issues/199
$this->assertSame('Cdyy', Pinyin::abbr('CGV电影院')->join(''));
$this->assertSame('CGVdyy', Pinyin::abbr('CGV电影院', false, true)->join(''));
$this->assertSame('CGV1990dyAy', Pinyin::abbr('CGV1990电影A院', false, true)->join(''));
}

public function test_name_abbr()
Expand Down

0 comments on commit 8255ee3

Please sign in to comment.