PHP 中英文混合排版中處理字串常用的函數
來源:互聯網
上載者:User
/*
我們在處理中文資料時,經常要處理一些情況,下面就是針對
這些情況,我做的一些函數,已經用在了實踐中
如果有問題,請與我聯絡
OICQ: 86804
*/
# 判斷某個位置是中文字元的左還是右半部分,或不是中文
# 傳回值 -1 左 0 不是中文字元 1 右
# 用法
/*
$a = 'this is 中文';
print is_chinese($a, 1); // 0
print is_chinese($a,8); // -1
print is_chinese($a,9); // 1
*/
function is_chinese(&$str, $location) {
$ch = true;
$i = $location;
while(ord($str[$i])>0xa0 && $i >= 0) {
$ch = !$ch;
$i --;
}
if($i != $location) {
$f_str = $ch ? 1: -1;
}
else {
$f_str = false;
}
return $f_str;
}
# 中文字串倒置函數
# 如果一個將一個有中文的字串用strrev倒過來,就會產生亂碼
/*
print cstrrev('this is 中文'); // 文中 si siht
*/
function cstrrev(&$str) {
$long = strlen($str);
for($f_str='', $chinese=false, $i=$long-1; $i>=0; $i--) {
if(ord($str[$i]) > 0xa0) {
$chinese = ! $chinese;
if($chinese == false) {
$f_str .= $str[$i].$str[$i+1];
}
}
else {
$f_str .= $str[$i];
}
}
return $f_str;
}
/* 中文字串截取函數
一些中文字串截取函數經常有一些問題,例如在一些自動換行程式中
$a=“1中2”;
經兩次截取後,
csubstr($str,$a,0,2);
csubstr($str, $a, 2,2)
由於載取位置指向“中”的右位元組,可能會是這樣的結果
1, 2
用本函數會產生正確的結果
1中, 2
*/
# start 開始位置,從0開始
# long = 0 則從start 一直取到字串尾
# ltor = true 時從左至右取字元,false 時到右到左取字元
# $cn_len 中文字元按位元組取還是字數取,如果按字數取,則一個中文當一個位元組計算
function csubstr(&$str, $start=0, $long=0, $ltor=true, $cn_len=2) {
if($long == 0) $long = strlen($str);
if($ltor == false) $str = cstrrev($str);