天天看點

PHP ckeditor對中文進行處理出現問号(??)的處理方案

今天在項目中遇到這樣一個需求,評論資訊内容很多,在背景評論清單展示時:如果字數小于50時,全部顯示。否則,顯示前50個字元+省略号。

本以為是很簡單的需求,于是乎就利用substr進行計算,寫了如下代碼,很快就完成了。

/**
     * 截取字元串
     * @param $content
     * @return string
     */
    static  public  function  getContent($content){
        $content=strip_tags($content);
        $contentLen=strlen($content);
        if($contentLen>100){
            $content=substr($content,0,100,'utf-8');
            $contentStr=$content.'...';
        }else{
            $contentStr=$content;
        }
        return $contentStr;
    }
           

測試時,由于評論全是英文,并沒有發現問題。經過多次測試,發現當評論有中文時,會出現??。

當時以為是編輯器的bug,經過多方檢查。發現php有個mb_substr()函數,這時可以用mb_substr()/mb_strcut這個函數,mb_substr() /mb_strcut的用法與substr()相似,隻是在mb_substr()/mb_strcut最後要加入多一個參數,以設定字元串的編碼,但是 一般的伺服器都沒打開php_mbstring.dll,需要在php.ini中把php_mbstring.dll打開。

明白了mb_substr()使用後,就寫了一個工具方法,完美解決了此問題。具體代碼如下:

/**
     * 截取字元串
     * @param $content
     * @return string
     */
    static  public  function  getContent($content){
        $content=strip_tags($content);
        $contentLen=mb_strlen($content);
        if($contentLen>100){
            $content=mb_substr($content,0,100,'utf-8');
            $contentStr=$content.'...';
        }else{
            $contentStr=$content;
        }
        return $contentStr;
    }
           

以上屬于個人見解,如有不正确之處,歡迎指正。