php截取中文的函數utf_substr

來源:互聯網
上載者:User
  1. $tmp = preg_replace('/[一-龥]/u','<@>','你好我是誰?123abc');
  2. /u是UTF-8
複製代碼

代碼1,PHP截取UTF-8字串,解決半字元問題

  1. /***

  2. * PHP截取UTF-8字串,解決半字元問題。utf_substr
  3. * 英文、數字(半形)為1位元組(8位),中文(全形)為3位元組
  4. * @return 取出的字串, 當$len小於等於0時, 會返回整個字串
  5. * @param $str 源字串
  6. * $len 左邊的子串的長度
  7. * @edit bbs.it-home.org
  8. function utf_substr($str,$len){
  9. for($i=0;$i<$len;$i++){
  10. $temp_str=substr($str,0,1);
  11. if(ord($temp_str) > 127){
  12. $i++;
  13. if($i<$len){
  14. $new_str[]=substr($str,0,3);
  15. $str=substr($str,3);
  16. }
  17. }else{
  18. $new_str[]=substr($str,0,1);
  19. $str=substr($str,1);
  20. }
  21. }
  22. return join($new_str);
  23. }

  24. //調用樣本

  25. $str = utf_substr('你好',4);
  26. echo $str;
  27. ?>

複製代碼

代碼2,截取utf-8字串函數

  1. /**

  2. * 截取utf-8字串
  3. * edit bbs.it-home.org
  4. */
  5. function cut_str($sourcestr,$cutlength){
  6. $returnstr='';
  7. $i=0;
  8. $n=0;
  9. $str_length=strlen($sourcestr);//字串的位元組數
  10. while (($n<$cutlength) and ($i<=$str_length)){
  11. $temp_str=substr($sourcestr,$i,1);
  12. $ascnum=Ord($temp_str);//得到字串中第$i位字元的ascii碼
  13. if ($ascnum>=224){ //如果ASCII位高與224,
  14. $returnstr=$returnstr.substr($sourcestr,$i,3); //根據UTF-8編碼規範,將3個連續的字元計為單個字元
  15. $i=$i+3; //實際Byte計為3
  16. $n++; //字串長度計1
  17. }elseif ($ascnum>=192){ //如果ASCII位高與192,
  18. $returnstr=$returnstr.substr($sourcestr,$i,2); //根據UTF-8編碼規範,將2個連續的字元計為單個字元
  19. $i=$i+2; //實際Byte計為2
  20. $n++; //字串長度計1
  21. }elseif ($ascnum>=65 && $ascnum<=90){ //如果是大寫字母,
  22. $returnstr=$returnstr.substr($sourcestr,$i,1);
  23. $i=$i+1; //實際的Byte數仍計1個
  24. $n++; //但考慮整體美觀,大寫字母計成一個高位字元
  25. }else{ //其他情況下,包括小寫字母和半形標點符號,
  26. $returnstr=$returnstr.substr($sourcestr,$i,1);
  27. $i=$i+1; //實際的Byte數計1個
  28. $n=$n+0.5; //小寫字母和半形標點等與半個高位字元寬...
  29. }
  30. }
  31. if ($str_length>$cutlength){
  32. $returnstr = $returnstr . "...";//超過長度時在尾處加上省略符號
  33. }
  34. return $returnstr;
  35. }

  36. //調用樣本

  37. $str = '你好!我好';
  38. $str = cut_str($str,3);
  39. echo $str;
  40. ?>

複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.