php 截取utf-8格式的字串

來源:互聯網
上載者:User
這篇文章主要介紹了php 截取utf-8格式的字串執行個體代碼的相關資料,並附執行個體代碼,需要的朋友可以參考下

php 截取utf-8格式的字串

php中,我們經常需要截取字串。英文字元佔用一個位元組,中文字元佔用兩個位元組,但中文字元佔用兩個位元組是相對於GBK編碼而言但是在時下國際流行的UTF8編碼中,一個中文字元佔用3個位元組。本文章向大家介紹一個php 截取utf-8格式字串的函數。

舉例說明:

function truncate_utf8_string($string, $length, $etc = '...') { $result = ''; $string = html_entity_decode ( trim ( strip_tags ( $string ) ), ENT_QUOTES, 'UTF-8' ); $strlen = strlen ( $string ); for($i = 0; (($i < $strlen) && ($length > 0)); $i ++) { if ($number = strpos ( str_pad ( decbin ( ord ( substr ( $string, $i, 1 ) ) ), 8, '0', STR_PAD_LEFT ), '0' )) {  if ($length < 1.0) {  break;  }  $result .= substr ( $string, $i, $number );  $length -= 1.0;  $i += $number - 1; } else {  $result .= substr ( $string, $i, 1 );  $length -= 0.5; } } $result = htmlspecialchars ( $result, ENT_QUOTES, 'UTF-8' ); if ($i < $strlen) { $result .= $etc; } return $result;}

如果需要截取utf-8格式的字串,直接調用這個函數即可。

<?php  $str="如果需要截取utf-8格式的字串,直接調用這個函數即可。";  echo truncate_utf8_string($str,10);//輸出結果:如果需要截取utf-8格...?>

以上就是本文的全部內容,希望對大家的學習有所協助。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.