php获取中文拼音首字母类和函数分享(2)


    foreach ( $words AS $word ) {          
        if ( $this->_isAscii($word) ) {//非中文
            $result[] = $word;
            continue;
        }
        $code = ( ord(substr($word,0,1)) ) * 1000 + (ord(substr($word,1,1)));
        //获取拼音首字母A--Z


        if ( ($i = $this->_search($code)) != -1 ){
            $result[] = $this->_pinyins[$i];
        }
    }
    return strtoupper(implode('', $result));
}


/**
 * _msubstr 获取中文字符串
 *
 * @access private
 * @param string $str
 * @param int    $start
 * @param int    $len
 * @return string
 */
private function _msubstr ($str, $start, $len) {
    $start  = $start * 2;
    $len    = $len * 2;
    $strlen = strlen($str);
    $result = '';
    for ( $i = 0; $i < $strlen; $i++ ) {
        if ( $i >= $start && $i < ($start + $len) ) {
            if ( ord(substr($str, $i, 1)) > 129 ) $result .= substr($str, $i, 2);
            else $result .= substr($str, $i, 1);
        }
        if ( ord(substr($str, $i, 1)) > 129 ) $i++;
    }
    return $result;
}


/**
 * _cutWord  字符串切分为数组 (汉字或者一个字符为单位)
 *
 * @access private
 * @param string $str
 * @return array
 */
private function _cutWord( $str ) {
    $words = array();
    while ( $str != "" ) {
        if ( $this->_isAscii($str) ) {//非中文
            $words[] = $str[0];
            $str = substr( $str, strlen($str[0]) );
        } else {
            $word = $this->_msubstr( $str, 0, 1 );
            $words[] = $word;
            $str = substr( $str,  strlen($word) );
        }
     }
     return $words;
}


/**
 * _isAscii 判断字符是否是ascii字符
 *
 * @access private
 * @param  string $char
 * @return bool
 */
private function _isAscii( $char ) {
    return ( ord( substr($char,0,1) ) < 160 );
}

/**
 * _isAsciis 判断字符串前3个字符是否是ascii字符
 *
 * @access private
 * @param  string $str
 * @return bool
 */
private function _isAsciis( $str ) {
    $len = strlen($str) >= 3 ? 3: 2;
    $chars = array();
    for( $i = 1; $i < $len -1; $i++ ){
        $chars[] = $this->_isAscii( $str[$i] ) ? 'yes':'no';
    }
    $result = array_count_values( $chars );
    if ( empty($result['no']) ){
        return true;
    }
    return false;
}



/**
 * _getChar 通过ASC码返回字母或者数字
 *
 * @access private
 * @param  string $ascii
 * @return string
 */
private function _getChar( $ascii ){
    if ( $ascii >= 48 && $ascii <= 57 ) {
        return chr($ascii);  //数字
    } elseif ( $ascii>=65 && $ascii<=90 ) {
        return chr($ascii);   // A--Z
    } elseif ($ascii>=97 && $ascii<=122 ) {
        return chr($ascii-32); // a--z
    } else {
        return '~'; //其他
    }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/c8bbdf23e36d4da81dd4227f352a1996.html