Home > php教程 > PHP源码 > PHP 截取中文字符

PHP 截取中文字符

PHP中文网
Release: 2016-05-25 17:10:52
Original
1135 people have browsed it

php代码

/**
 * PHP 截取中文字符
 * echo cn_substr_utf8($cc,65)
 */
function cn_substr_utf8($str, $length, $start=0)
{
$lgocl_str=$str;
//echo strlen($lgocl_str)."||".$length;
    if(strlen($str) < $start+1)
    {
        return &#39;&#39;;
    }
    preg_match_all("/./su", $str, $ar);
    $str = &#39;&#39;;
    $tstr = &#39;&#39;;

    //为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取
    for($i=0; isset($ar[0][$i]); $i++)
    {
        if(strlen($tstr) < $start)
        {
            $tstr .= $ar[0][$i];
        }
        else
        {
            if(strlen($str) < $length + strlen($ar[0][$i]) )
            {
                $str .= $ar[0][$i];
            }
            else
            {
                break;
            }
        }
    }
    if(strlen($lgocl_str)<=$length){
    }else{
    $str.="...";
    }
    return $str;
}
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template