<?php
/**
 * 中文 - 拼音类
 * @copyright reginx.com
 * $Id$
 */
class py_lib {

    /**
     * 获取字符串拼音
     *
     * @param unknown_type $cnstr
     */
    public static function get($scnstr , $pstr = '_'){
        $num = array(
                0    => array(0,1,2,3,4,5,6,7,8,9),
                1    => array('零' , '壹' , '贰' , '叁' , '肆' , '伍' , '陆' , '柒' , '捌' , '玖')
        );
        $ret = '';
        $scnstr = str_replace($num[0] , $num[1] , $scnstr);
        $cnstr = preg_replace('/\s*/' , '' , $scnstr ? $scnstr : ' ');
        if($cnstr != ''){
            $cnstr = empty($cnstr) ? '' : str_replace($pstr , '' , trim($cnstr));
            $lst = self::split($cnstr);
            if(empty($lst[0])){
                unset($lst[0]);
            }
            $ret = join($pstr , $lst);
            $res = core::getobj('py_tab')->where("cn in ('" . join('\',\'' , $lst) . "')")->getall();
            foreach ($res as $k => $v){
                $ret = str_replace($v['cn'] , $v['py'] , $ret);
            }
            unset($lst);
        }else{
            $ret = $scnstr;
        }
        // - 清除非拼音内容
        $ret = preg_replace('/\_?[^\w\-\_]+/i' , '' , $ret);
        if(substr($ret ,0 , 1) == '_'){
        	$ret = substr($ret , 1);
        }
        if(substr($ret , -1) == '_'){
        	$ret = substr($ret , 0  , -1);
        }
        if($GLOBALS['_APP']['utype'] == '2'){
            $ret = strtolower(preg_replace('/[A-Z][^A-Z]+/' , '\\0-' , $ret));
            if(substr($ret , -1) == '-'){
            	$ret = substr($ret , 0  , -1);
            }
        }
        return $ret;
    }

    /**
     * 宽字符串分割 (utf-8)
     *
     * @param unknown_type $str
     * @return unknown
     */
    public static function split($str){
        $str = preg_replace('/[^\x{4e00}-\x{9fa5}\w]+/u' , '' , $str);
        $str = preg_split('/(?<!^)(?!$)/u', $str);
        $str = preg_replace('/\-?(\w+)\-?/' , '\1' , join('-', $str));
        $str = preg_replace('/\w+/' , '-\0-' , $str);
        return explode('-' , $str);
    }
}
?>