<?php
class PinYin {
public $pinyin = array();
/**
* 初始化GBK码表对应值
*/
public function __construct(){
// py.dic格式化后的数组
$this -> pinyin = $pinyin_dictory;
}
/**
* 输入字符串,以及要返回的数据形态
* @param type $s 字符串原值
* @param type $first 只要为真返回汉字首字母
* @return type
*/
public function str2py($s, $first = false)
{
//空格的默认转换字符
$s = preg_replace(“/\s/is”, “_”, $s);
//过滤掉所有的非法字符;~,`,!,@#$%^&*()-=+{}[]|\:;”‘<>.?/
$s = preg_replace(“/(|\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\+|\=|\{|\}|\[|\]|\||\\|\:|\;|\”|\’|\<|\,|\>|\.|\?|\/)/is”, “”, $s);
//初始化
$py = array();
// 加入这一句,自动识别utf-8
if(strlen(“拼音”) > 4)
{
$s = iconv(‘utf-8’, ‘gbk’, $s);//强制转换为GBK编码
}
//循环处理
for ($i = 0;$i < strlen($s);$i++){
if (ord($s[$i]) > 128){
$py[] = $this -> asi2py(ord($s[$i]) +
(ord($s[$i + 1]) << 8), $first);
$i++;
} else {
//处理小写a元素和大写A元素
if ($s[$i] == ‘a’ || $s[$i] == ‘A’) {
$py[] = $s[$i].’*’;
} else {
$py[] = $s[$i];
}
}
}
//返回结果
return $py;
}
/**
* 查找汉字对应的拼音
* @param type $a
* @param type $first
* @return type
*/
public function asi2py($a, $first)
{
$py = $this -> pinyin;
foreach ($py as $k => $p){
if (array_search($a, $p) === false){
} else{
if ($first) {
return substr(key($py), 0, 1);
}
return key($py);
}
next($py);
}
}
/**
* 根据汉字获取汉字全拼
* @param type $string
* @return type
*/
public function getQp($string)
{
return join($this->str2py($string),”);
}
/**
*
* @param type $string
* @return 根据汉字获获取简拼(汉字首字母)
*/
public function getJp($string)
{
return join($this->str2py($string,1), ”);
}
/**
* 根据汉字获取汉字简拼 同时为每个汉字设置分割符号
* @param type $string
* @return type
*/
public function getJpDelimiter($string, $delimiter)
{
$jp = $this->str2py($string,1);
$t1 = “”;
foreach($jp as $k => $v) {
if (is_numeric($v)) {
if ($t1) {
$jp[$t1] .= $v;
unset($jp[$k]);
} else {
$t1 = $k;
}
} else {
$t1 = “”;
}
}
return join($jp,$delimiter);
}
/**
* 根据汉字获取汉字全拼 同时为每个汉字设置分割符号
* @param type $string
* @return type
*/
public function getQpDelimiter($string, $delimiter)
{
$qp = $this->str2py($string);
$t1 = $t2 = “”;
foreach($qp as $k => $v) {
if (is_numeric($v)) {
if ($t1) {
$qp[$t1] .= $v;
unset($qp[$k]);
} else {
$t1 = $k;
}
}
else if($this->checkPy($v)) {
if($v == ‘a*’){
$qp[$k] = $v = ‘a’;
} else if($v == ‘A*’) {
$qp[$k] = $v = ‘A’;
}
if ($t2) {
$qp[$t2] .= $v;
unset($qp[$k]);
} else {
$t2 = $k;
}
} else {
$t1 = “”;
$t2 = “”;
}
}
return join($qp, $delimiter);
}
public function checkPy($py)
{
if ($py == ‘a’) {
return false;
}
else if ($py == ‘a*’ || $py == ‘A*’ || strlen($py) == 1) {
return true;
} else {
return false;
}
}
}