關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • PHP 分割中文字

    Posted on September 14th, 2006 Sam Tang 1 comment

    PHP 內建的 substr 函式可以分割文字,但要分割的文字如果包括有中文字往往會遇到問題,這可以用 mb_substr() 來做。mb_substr() 的用法與 substr() 很相似,只是在 mb_substr() 最後要加入多一個參數,以設定字串的編碼,但要先讓 PHP 支援 mbstring 才可以。

    在編譯 PHP 時加入 --enable-mbstring 選擇就可以加入 mbstring 模組了。以下是 mb_substr() 的使用方法:

    CODE:
    1. <?php
    2. $string = '這是測試用的中文字';
    3. $string = mb_substr($string, -1, 3, 'BIG-5');
    4. echo $string;  // 會輸出 '中文字'
    5. ?>

    以上的第三行要注意,將 BIG-5 修改成中文字所用的編碼,例如 UTF-8。


     

    One response to “PHP 分割中文字”

    1. [...] PHP 分割中文字 – Real-Blog PHP 內建的 substr 函式可以分割文字,但要分割的文字如果包括有中文字往往會遇到問題,這可以用 mb_substr() 來做 [...]

    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word