class pinyin{
/*
是否將拼音檔案讀取到記憶體內,損耗少許記憶體,幾百kb的樣子,速度可以略有提升,
*/
var $ismemorycache = 1;
/*
是否只擷取首字母
*/
var $isfrist = 1;
/*
拼音矩陣檔案地址
*/
var $path = "py.qdb";
/*
記憶體拼音矩陣
*/
var $memorycache;
/*
拼音檔案控制代碼
*/
var $handle;
/*
轉換髮生錯誤盒子
*/
var $errormsgbox;
/*
轉換結果
*/
var $result;
var $array = array();
var $n_t = array("ā" => "a","á" => "a","ǎ" => "a","à" => "a","?" => "a",
"ō" => "o","ó" => "o","ǒ" => "o","ò" => "o",
"ē" => "e","é" => "e","ě" => "e","è" => "e","ê" => "e",
"ī" => "i","í" => "i","ǐ" => "i","ì" => "i",
"ū" => "u","ú" => "u","ǔ" => "u","ù" => "u",
"ǖ" => "v","ǘ" => "v","ǚ" => "v","ǜ" => "v","ü" => "v"
);
/*
轉換入口
@params $str 所需轉換字元,$istonemark 是否保留音標 $suffix 尾綴,預設為空白格
*/
function chinesetopinyin($str,$istonemark = 0,$suffix = ""){
$this->py($str,$istonemark,$suffix);
return $this -> result;
}
function get(){
return $this -> result;
}
function py($str,$n = 0,$s = ""){
$strlength = strlen($str);
if($strlength == 0){ return ""; }
$this->result = "";
if(is_array($str)){
foreach($str as $key => $val){
$str[$key] = $this->py($val,$n,$s);
}
return;
}
if(empty($this->handle)){
if(!file_exists($this->path)){
$this->addoneerrormsg(1,"拼音檔案路徑不存在");
return false;
}
if(is_array($str)){
foreach($str as $key => $val){
$str[$key] = $this->py($val,$n,$s);
}
}
if($this -> ismemorycache){
if(!$this->memorycache){
$this->memorycache = file_get_contents($this->path);
for($i = 0 ; $i < $strlength ; $i++){
$ord1 = ord(substr($str,$i,1));
if($ord1 > 128){
$ord2 = ord(substr($str, ++$i, 1));
if(!isset($this->array[$ord1][$ord2])){
$leng = ($ord1 - 129) * ((254 - 63) * 8 + 2) + ($ord2 - 64) * 8;
$this->array[$ord1][$ord2] = trim(substr($this->memorycache,$leng,8));
}
$strtrlen = $this->isfrist ? 1 : 8;
$this->result .= substr($this ->array[$ord1][$ord2],0,$strtrlen).$s;
}else{
$this->result .= substr($str,$i,1);
}
}
}
}else{
$this->handle = fopen($this->path,"r");
for($i = 0 ; $i < $strlength ; $i++){
$ord1 = ord(substr($str,$i,1));
if($ord1 > 128){
$ord2 = ord(substr($str, ++$i, 1));
if(!isset($this->array[$ord1][$ord2])){
$leng = ($ord1 - 129) * ((254 - 63) * 8 + 2) + ($ord2 - 64) * 8;
fseek($this -> handle,$leng);
$this->array[$ord1][$ord2] = trim(fgets($this->handle,8));
}
$strtrlen = $this->isfrist ? 1 : 8;
$this->result .= substr($this ->array[$ord1][$ord2],0,$strtrlen).$s;
}else{ $this->result .= substr($str,$i,1); }
}
}
if(!$n){ $this -> result = strtr($this -> result,$this -> n_t);}
}
}
function addoneerrormsg($no,$reason){
$this->errormsgbox[] = "<b>error:</b>" . $no . "," . $reason;
}
function showerrormsg(){
foreach($this->errormsgbox as $val){
echo $val."rnrn</br></br>";
}
}
function __destruct(){
if(is_array($this->errormsgbox)){
$this->showerrormsg();
}
}
}