mb_substr()----------php

來源:互聯網
上載者:User

標籤:style   color   io   os   ar   div   問題   sp   cti   

        PHP substr()函數可以分割文字,但要分割的文字如果包括中文字元往往會遇到問題,這時可以用mb_substr()/mb_strcut這個函數,mb_substr() /mb_strcut的用法與substr()相似,只是在mb_substr()/mb_strcut最後要加入多一個參數,以設定字串的編碼,但是 一般的伺服器都沒開啟php_mbstring.dll,需要在php.ini中把php_mbstring.dll開啟。

<?php

echo mb_substr(‘我們都是好孩子hehe‘,0,9);

?>

輸出:我們都

現在我們加上字元集utf-8

<?php echo  mb_substr( ‘我們都是好孩子hehe‘ ,0,9, ‘utf-8‘ );

?>

輸出:我們都是好孩子he

第一個是以三個位元組為一個中文,這就是utf-8編碼的特點,下面加上utf-8字元集說明,所以,是以一個字為單位來截取的

 下面是ecshop裡面的截取UTF-8編碼下字串的函數

function sub_str($str, $length = 0, $append = true)

{

    $str = trim($str);

    $strlength = strlen($str);

    if ($length == 0 || $length >= $strlength)

    { return $str;  //截取長度等於0或大於等於本字串的長度,返回字串本身

    }

    elseif ($length < 0)  //如果截取長度為負數

    { $length = $strlength + $length;//那麼截取長度就等於字串長度減去截取長度

        if ($length < 0)

        {$length = $strlength;//如果截取長度的絕對值大於字串本身長度,則截取長度取字串本身的長度

        }

    }

    if (function_exists(‘mb_substr‘))

    {$newstr = mb_substr($str, 0, $length, EC_CHARSET);

    }

    elseif (function_exists(‘iconv_substr‘))

    {$newstr = iconv_substr($str, 0, $length, EC_CHARSET);

    }

    else

    {//$newstr = trim_right(substr($str, 0, $length));

        $newstr = substr($str, 0, $length);

    }

    if ($append && $str != $newstr)

    {$newstr .= ‘...‘;

    }

  return $newstr;

}





mb_substr()----------php

聯繫我們

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