标题:
GBK码汉字转拼音
[打印本页]
作者:
php
时间:
2007-7-14 10:11
标题:
GBK码汉字转拼音
不知道什么时候会用上,看着不错,先拿过来了
用的时候需要下载py.dat那个文件放在当前目录下
http://www.hightman.cn/demo/py.dat
原文连接:
http://www.hightman.cn/bbs/forumdisplay.php?fid=9&
;page=1
<
?
php
class
my_Getpy
{
var
$
_dat
=
'py.dat'
;
var
$
_fd
=
false
;
function
my_Getpy
(
$
pdat
=
''
)
{
if
(
''
!
=
$
pdat
)
$
this
-
>
_dat
=
$
pdat
;
}
function
load
(
$
pdat
=
''
)
{
if
(
''
=
=
$
pdat
)
$
pdat
=
$
this
-
>
_dat
;
$
this
-
>
unload
(
)
;
$
this
-
>
_fd
=
@
fopen
(
$
pdat
,
'rb'
)
;
if
(
!
$
this
-
>
_fd
)
{
trigger_error
(
"unable to load PinYin data file `$pdat`"
,
E_USER_WARNING
)
;
return
false
;
}
return
true
;
}
function
unload
(
)
{
if
(
$
this
-
>
_fd
)
{
@
fclose
(
$
this
-
>
_fd
)
;
$
this
-
>
_fd
=
false
;
}
}
function
get
(
$
zh
)
{
if
(
strlen
(
$
zh
)
!
=
2
)
{
trigger_error
(
"`$zh` is not a valid GBK hanzi"
,
E_USER_WARNING
)
;
return
false
;
}
if
(
!
$
this
-
>
_fd
&
&
!
$
this
-
>
load
(
)
)
return
false
;
$
high
=
ord
(
$
zh
[
0
]
)
-
0x81
;
$
low
=
ord
(
$
zh
[
1
]
)
-
0x40
;
// 计算偏移位置
$
nz
=
(
$
ord0
-
0x81
)
;
$
off
=
(
$
high
<
<
8
)
+
$
low
-
(
$
high
*
0x40
)
;
// 判断 off 值
if
(
$
off
<
0
)
{
trigger_error
(
"`$zh` is not a valid GBK hanzi-2"
,
E_USER_WARNING
)
;
return
false
;
}
fseek
(
$
this
-
>
_fd
,
$
off
*
8
,
SEEK_SET
)
;
$
ret
=
fread
(
$
this
-
>
_fd
,
8
)
;
$
ret
=
unpack
(
'a8py'
,
$
ret
)
;
return
$
ret
[
'py'
]
;
}
function
_my_Getpy
(
)
{
$
this
-
>
_unload
(
)
;
}
}
// demo 测试例子
?
>
<
title
>
GBK码汉字转拼音
-
by hightman
<
/
title
>
<
h1
>
GBK码汉字转拼音
-
by hightman
<
/
h1
>
<
form
method
=
get
>
输入汉字试试:
<
input
type
=
"text"
size
=
"16"
name
=
"zh"
>
<
input
type
=
"submit"
>
<
/
form
>
<
?
php
if
(
$
str
=
$
_GET
[
'zh'
]
)
{
$
py
=
new
my_Getpy
;
$
len
=
strlen
(
$
str
)
;
$
ret
=
''
;
for
(
$
i
=
0
;
$
i
<
$
len
;
$
i
+
+
)
{
if
(
ord
(
$
str
[
$
i
]
)
>
0x80
)
{
$
xx
=
$
py
-
>
get
(
substr
(
$
str
,
$
i
,
2
)
)
;
$
ret
.
=
(
$
xx
?
$
xx
.
' '
:
substr
(
$
str
,
$
i
,
2
)
)
;
$
i
+
+
;
}
else
{
$
ret
.
=
$
str
[
$
i
]
;
}
}
$
py
-
>
unload
(
)
;
echo
"字串 `<font color=red>{$str}</font>` 的拼音是: <font color=red>{$ret}</font>\n"
;
}
?
>
欢迎光临 编程开发论坛 (http://bbs.lihuasoft.net/)
Powered by Discuz! 6.0.0