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

PHP 截取中文字符

PHP中文网
PHP中文网Original
2016-05-25 17:10:521122browse

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;
}

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
Previous article:PHP二分查找实例Next article:php冒泡排序和快速排序