UTF-8編碼時擷取字串和計算長度的函數
資料轉貼自: Lukin zone
改寫討論區程式時剛好需要用到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | < ?php // 支援中文的 substr(string,length[,start]) function cnsubstr($l1,$l2,$l3=0) { $I2 = "/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/"; preg_match_all($I2,$l1,$I3); if (count($I3[0]) - $l3 > $l2) { return implode('',array_slice($I3[0],$l3,$l2))."..."; } return implode('',array_slice($I3[0],$l3,$l2)); } // 計算中文字串長度 function len($l1) { $I2 = "/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/"; preg_match_all($I2,$l1,$I3); return count($I3[0]); } ?> |