php中文字串截取無亂碼的方法_PHP教程

來源:互聯網
上載者:User
在網上找到了很多關於php截取中文方法,其中最多的還是講到使用mb_substr函數來截取了,這個函數需要php.ini中一個拓展支援,但我沒許可權修改只有另想辦法。

substr截取

substr() 函數返回字串的一部分。

代碼如下 複製代碼
$rest = substr("我是中國人", -1); // returns "亂碼"
echo $rest.'
';
$rest = substr("abcdef", -2); // returns "ef"
echo $rest.'
';
$rest = substr("abcdef", -3, 1); // returns "d"
echo $rest.'
';
?>

接著百度goole說可以mb_substr截取

代碼如下 複製代碼


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

運行機制提示

Fatal error: Call to undefined function mb_substr()...

後來有朋友告訴我是一般的伺服器都沒開啟php_mbstring.dll,需要在php.ini中把php_mbstring.dll開啟,找到idc商不開,只有另想辦法

代碼如下 複製代碼

function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
if(function_exists("mb_substr"))
return mb_substr($str, $start, $length, $charset);
elseif(function_exists('iconv_substr')) {
return iconv_substr($str,$start,$length,$charset);
}
$re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
$re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
$re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
$re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("",array_slice($match[0], $start, $length));
if($suffix) return $slice."…";
return $slice;
}

這個正好解決了所有問題了,看上是按字元編碼來進行截取了

http://www.bkjia.com/PHPjc/632743.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/632743.htmlTechArticle在網上找到了很多關於php截取中文方法,其中最多的還是講到使用mb_substr函數來截取了,這個函數需要php.ini中一個拓展支援,但我沒許可權修...

  • 聯繫我們

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