Home >php教程 >PHP源码 >php 截取中文字符串实现程序

php 截取中文字符串实现程序

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-08 17:24:131103browse

在php中我们截取字符串可以使用自带的函数,但是自带的函数不支持中文截取,如果需要截取中文字符串我们需要现做一些操作,下面我来给各位朋友介绍。

<script>ec(2);</script>

针对GB2312的代码

 代码如下 复制代码

//$str是要截取的字符串
//$start是要截取的字符的开始位置
//$len是指要截取的字符长度
function sub_str($str, $start, $len) {
        $tmpstr = "";
        $strlen = $start + $len;
        for($i = 0; $i             if(ord(substr($str, $i, 1)) > 0xa0) {
                $tmpstr .= substr($str, $i, 2);
                $i++;
            } else
                $tmpstr .= substr($str, $i, 1);
        }
        return $tmpstr."...";
}

针对uft8

 代码如下 复制代码

//截取utf8字符串
function utf8substr($str, $from, $len)
{
    return preg_replace('#^(?:[x00-x7f]|[xc0-xff][x80-xbf]+){0,'.$from.'}'.
                       '((?:[x00-x7f]|[xc0-xff][x80-xbf]+){0,'.$len.'}).*#s',
                       '$1',$str);
}
?>

上面的方法肯定不实用,因为我希望可以自动识别支持任何编码的字符串截取,后来找到一个还算可以的分享给各位朋友。

 代码如下 复制代码

/**
 * @package     BugFree
 * @version     $Id: FunctionsMain.inc.php,v 1.32 2005/09/24 11:38:37 wwccss Exp $
 *
 *
 * Return part of a string(Enhance the function substr())
 *
 * @author                  Chunsheng Wang
 * @param string  $String  the string to cut.
 * @param int     $Length  the length of returned string.
 * @param booble  $Append  whether append "...": false|true
 * @return string           the cutted string.
 */
function sysSubStr($String,$Length,$Append = false)
{
    if (strlen($String)     {
        return $String;
    }
    else
    {
        $I = 0;
        while ($I         {
            $StringTMP = substr($String,$I,1);
            if ( ord($StringTMP) >=224 )
            {
                $StringTMP = substr($String,$I,3);
                $I = $I + 3;
            }
            elseif( ord($StringTMP) >=192 )
            {
                $StringTMP = substr($String,$I,2);
                $I = $I + 2;
            }
            else
            {
                $I = $I + 1;
            }
            $StringLast[] = $StringTMP;
        }
        $StringLast = implode("",$StringLast);
        if($Append)
        {
            $StringLast .= "...";
        }
        return $StringLast;
    }
}

$String = "www.111cn.net 走在中国自动化测试的前沿";
$Length = "18";
$Append = false;
echo sysSubStr($String,$Length,$Append);
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn