From 8255ee3233a698a13ef049870b3a70a9fc723af5 Mon Sep 17 00:00:00 2001 From: overtrue Date: Tue, 19 Mar 2024 16:31:46 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=96=E9=A6=96=E5=AD=97=E6=AF=8D?= =?UTF-8?q?=E6=97=B6=EF=BC=8C=E8=83=BD=E5=90=A6=E4=BF=9D=E7=95=99=E5=AE=8C?= =?UTF-8?q?=E6=95=B4=E7=9A=84=E8=8B=B1=E6=96=87=20#199?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Pinyin.php | 9 +++++++-- tests/PinyinTest.php | 5 +++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/Pinyin.php b/src/Pinyin.php index 7f21864e..157a4f03 100644 --- a/src/Pinyin.php +++ b/src/Pinyin.php @@ -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); }); diff --git a/tests/PinyinTest.php b/tests/PinyinTest.php index bc5da342..ba9be2dc 100755 --- a/tests/PinyinTest.php +++ b/tests/PinyinTest.php @@ -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()