【收藏】php生成中文汉字首拼音实用类
在实际项目中,我们可能要用到把汉字生成拼音存到数据库中,比如新闻标题生成拼音做url,或者把分类项取首拼保存方便查询,应用场景很多。我现在做的项目是把城市分站生成首拼音做二级域名,现在是我正在用的类,分享给大家。
代码如下 | 复制代码 |
/** * 汉字拼音首字母工具类 * 注: 英文的字串:不变返回(包括数字) eg .abc123 => abc123 * 中文字符串:返回拼音首字符 eg. 湖南 => HN * 中英混合串: 返回拼音首字符和英文 eg. 我i我j => WIWJ * eg. * $py = new str2PY(); * * $result = $py->getInitials('周杰伦'); * * //获取首字母 * $result = $py->getFirstString('abc'); //A * $resutl = $py->getFirstString("一聚教程"); //y * */ class str2py { private $_pinyins = array( => 'A', => 'B', => 'C', => 'D', => 'E', => 'F', => 'G', => 'H', => 'J', => 'K', => 'L', => 'M', => 'N', => 'O', => 'P', => 'Q', => 'R', => 'S', => 'T', => 'W', => 'X', => 'Y', => 'Z', ); private $_charset = null; /** * 构造函数, 指定需要的编码 default: utf-8 * 支持utf-8, gb2312 * * @param unknown_type $charset */ public function __construct($charset = 'utf-8') { $this->_charset = $charset; } /** * 中文字符串 substr * * @param string $str * @param int $start * @param int $len * @return string */ private function _msubstr($str, $start, $len) { $start = $start * 2; $len = $len * 2; $strlen = strlen($str); $result = ''; for ($i = 0; $i { if ($i >= $start && $i { if (ord(substr($str, $i, 1)) > 129) { $result .= substr($str, $i, 2); } else { $result .= substr($str, $i, 1); } } if (ord(substr($str, $i, 1)) > 129) { $i++; } } return $result; } /** * 字符串切分为数组 (汉字或者一个字符为单位) * * @param string $str * @return array */ private function _cutWord($str) { $words = array(); while ($str != "") { if ($this->_isAscii($str)) {/* 非中文 */ $words[] = $str[0]; $str = substr($str, strlen($str[0])); } else { $word = $this->_msubstr($str, 0, 1); $words[] = $word; $str = substr($str, strlen($word)); } } return $words; } /** * 判断字符是否是ascii字符 * * @param string $char * @return bool */ private function _isAscii($char) { return ( ord(substr($char, 0, 1)) } /** * 判断字符串前3个字符是否是ascii字符 * * @param string $str * @return bool */ private function _isAsciis($str) { $len = strlen($str) >= 3 ? 3 : 2; $chars = array(); for ($i = 1; $i { $chars[] = $this->_isAscii($str[$i]) ? 'yes' : 'no'; } $result = array_count_values($chars); if (empty($result['no'])) { return true; } return false; } /** * 获取中文字串的拼音首字符 * * @param string $str * @return string */ public function getInitials($str) { if (empty($str)) return ''; if ($this->_isAscii($str[0]) && $this->_isAsciis($str)) { return $str; } $result = array(); if ($this->_charset == 'utf-8') { $str = iconv('utf-8', 'gb2312', $str); } $words = $this->_cutWord($str); foreach ($words as $word) { if ($this->_isAscii($word)) {/* 非中文 */ $result[] = $word; continue; } $code = ord(substr($word, 0, 1)) * 1000 + ord(substr($word, 1, 1)); /* 获取拼音首字母A--Z */ if (($i = $this->_search($code)) != -1) { $result[] = $this->_pinyins[$i]; } } return strtoupper(implode('', $result)); } /** * 20140624 wangtianbao 获取首字母 * @param string $str * @return string */ public function getFirstString($str) { //先把中文转换成字母 $new_string = $this->getInitials($str); if (empty($new_string)) { return ''; } else { return strtoupper(substr($new_string, 0, 1)); } } private function _getChar($ascii) { if ($ascii >= 48 && $ascii { return chr($ascii); /* 数字 */ } elseif ($ascii >= 65 && $ascii { return chr($ascii); /* A--Z */ } elseif ($ascii >= 97 && $ascii { return chr($ascii - 32); /* a--z */ } else { return '-'; /* 其他 */ } } /** * 查找需要的汉字内码(gb2312) 对应的拼音字符( 二分法 ) * * @param int $code * @return int */ private function _search($code) { $data = array_keys($this->_pinyins); $lower = 0; $upper = sizeof($data) - 1; $middle = (int) round(($lower + $upper) / 2); if ($code return -1; for (;;) { if ($lower > $upper) { return $data[$lower - 1]; } $tmp = (int) round(($lower + $upper) / 2); if (!isset($data[$tmp])) { return $data[$middle]; } else { $middle = $tmp; } if ($data[$middle] { $lower = (int) $middle + 1; } else if ($data[$middle] == $code) { return $data[$middle]; } else { $upper = (int) $middle - 1; } } } } |
如果大家感兴趣,有深入学习的想法,可以把它改成生成全拼音。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible
