Example of php Chinese characters to pinyin
- 2021-01-19 22:03:53
- OfStack
<?php
class Helper_Spell{
public $spellArray = array();
static public function getArray() {
return unserialize(file_get_contents('pytable_without_tune.txt'));
}
/**
* @desc Gets the first letter of the string
* @param $string The string to convert
* @param $isOne Whether to take the first letter
* @param $upper Whether to convert to uppercase
* @return string
*
* Such as: getChineseFirstChar(' I am a writer ') The first character of all letters + lowercase
* return "wo"
*
* Such as: getChineseFirstChar(' I am a writer ',true) The first letter of the initial character + lowercase
* return "w"
*
* Such as: getChineseFirstChar(' I am a writer ',true,true) The first letter of the initial character + A capital
* return "W"
*
* Such as: getChineseFirstChar(' I am a writer ',false,true) The first character of all letters + A capital
* return "WO"
*/
static public function getChineseFirstChar($string,$isOne=false,$upper=false) {
$spellArray = self::getArray();
$str_arr = self::utf8_str_split($string,1); // Split a string into an array
if(preg_match('/^[\x{4e00}-\x{9fa5}]+$/u',$str_arr[0])) { // Determine whether it is a Chinese character
$chinese = $spellArray[$str_arr[0]];
$result = $chinese[0];
}else {
$result = $str_arr[0];
}
$result = $isOne ? substr($result,0,1) : $result;
return $upper?strtoupper($result):$result;
}
/**
* @desc Converts a string to a pinyin string
* @param $string Chinese character string
* @param $upper Whether the capital
* @return string
*
* Such as: getChineseChar(' I am a writer '); All strings + lowercase
* return "wo shi zuo zhe"
*
* Such as: getChineseChar(' I am a writer ',true); The first letter + lowercase
* return "w s z z"
*
* Such as: getChineseChar(' I am a writer ',true,true); The first letter + A capital
* return "W S Z Z"
*
* Such as: getChineseChar(' I am a writer ',false,true); The first letter + A capital
* return "WO SHI ZUO ZHE"
*/
static public function getChineseChar($string,$isOne=false,$upper=false) {
global $spellArray;
$str_arr = self::utf8_str_split($string,1); // Split a string into an array
$result = array();
foreach($str_arr as $char)
{
if(preg_match('/^[\x{4e00}-\x{9fa5}]+$/u',$char))
{
$chinese = $spellArray[$char];
$chinese = $chinese[0];
}else{
$chinese=$char;
}
$chinese = $isOne ? substr($chinese,0,1) : $chinese;
$result[] = $upper ? strtoupper($chinese) : $chinese;
}
return implode(' ',$result);
}
/**
* @desc Converts strings to arrays
* @param $str The array to convert
* @param $split_len
* @return array
*/
private function utf8_str_split($str,$split_len=1) {
if(!preg_match('/^[0-9]+$/', $split_len) || $split_len < 1) {
return FALSE;
}
$len = mb_strlen($str, 'UTF-8');
if ($len <= $split_len) {
return array($str);
}
preg_match_all('/.{'.$split_len.'}|[^\x00]{1,'.$split_len.'}$/us', $str, $ar);
return $ar[0];
}
}