class Helper_Spell{
public $spellArray = array();
static public function getArray() {
return unserialize(file_get_contents('pytable_without_tune.txt'));
}
/**
* @desc Get the first letter of the string
* @param $string The string to be converted
* @param $isOne Whether to take the first letter
* @param $upper Whether to convert to uppercase
* @return string
*
* For example: getChineseFirstChar('I am the author') The first character is all letters + lowercase
* return "wo"
*
* For example: getChineseFirstChar( 'I am the author',true) The first character of the first character + lowercase
* return "w"
*
* For example: getChineseFirstChar('I am the author',true,true) The first character of the first character + uppercase
* return "W"
*
* For example: getChineseFirstChar('I am the author',false,true) The first character is all letters+uppercase
* return "WO"
*/
static public function getChineseFirstChar($string,$isOne=false,$upper=false) {
$spellArray = self::getArray();
$str_arr = self::utf8_str_split($string,1); //将字符串拆分成数组
if(preg_match('/^[x{4e00}-x{9fa5}]+$/u',$str_arr[0])) { //判断是否是汉字
$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 Convert the string into a pinyin string
* @param $string Chinese character string
* @param $upper Whether to capitalize
* @return string
*
* For example: getChineseChar('I am the author'); All strings + lowercase
* return "wo shi zuo zhe"
*
* For example: getChineseChar('I am the author',true); First letter + lowercase
* return "w s z z"
* *
* For example: getChineseChar('I am the author',true,true); initial letter + uppercase
* return "W S Z Z"
*
* For example: getChineseChar('I am the author',false,true); initial letter + 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); //将字符串拆分成数组
$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 Convert string to array
* @param $str The array to be converted
* @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];
}
}