首頁 > 後端開發 > php教程 > PHP 截取 中文

PHP 截取 中文

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
發布: 2016-06-23 14:31:46
原創
936 人瀏覽過

函数巧妙地运用了正则表达式, 用起来很方便, 就像 substr 的用法一样, 可以正向截取也可反相截取, 思路值得学习.

PHP代码:

function c_substr ( $string,  $from,  $length =  null ){

     preg_match_all ( '/[x80-xff]?./',  $string,  $match );

     if ( is_null ( $length )){

         $result =  implode ( '',  array_slice ( $match [ 0 ],  $from ));

     } else {

         $result =  implode ( '',  array_slice ( $match [ 0 ],  $from,  $length ));

     }

     return  $result;

$str =  "zhon华人min共和guo";

$from =  3;

$length =  7;

echo (c_substr ( $str,  $from,  $length ));

// 输出: n华人min共

//还有utf-8的

Regarding windix's function to handle UTF-8 strings:

one can use the "u" modifier on the regular expression so that the pattern string is treated as UTF-8

(available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32).

This way the function works for other encodings too (like Greek for example).

The modified function would read like this:

function utf8_substr ( $str, $start )  {

$null =  "";

    preg_match_all ( "/./u",  $str,  $ar );

    if ( func_num_args () >=  3 )  {

        $end =  func_get_arg ( 2 );

        return  join ( $null,  array_slice ( $ar [ 0 ], $start, $end ));

    }  else  {

        return  join ( $null,  array_slice ( $ar [ 0 ], $start ));

    }

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
php正規截取url中網域後的內容
來自於 1970-01-01 08:00:00
0
0
0
如何截斷取得HTML表格中的錨點標籤文本
來自於 1970-01-01 08:00:00
0
0
0
ubuntu下存取php中文網自動定位到行動版?
來自於 1970-01-01 08:00:00
0
0
0
ruby讀取txt後,txt中的中文亂碼
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板