function str_cut($string, $length, $dot = '...')
{
$strlen = strlen($string);
if($strlen <= $length) return $string;
$string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
$strcut = '';
if(strtolower(CHARSET) == 'utf-8')
{
$n = $tn = $noc = 0;
while($n < $strlen)
{
$t = ord($string[$n]);
if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1; $n++; $noc++;
} elseif(194 <= $t && $t <= 223) {
$tn = 2; $n += 2; $noc += 2;
} elseif(224 <= $t && $t < 239) {
$tn = 3; $n += 3; $noc += 2;
} elseif(240 <= $t && $t <= 247) {
$tn = 4; $n += 4; $noc += 2;
} elseif(248 <= $t && $t <= 251) {
$tn = 5; $n += 5; $noc += 2;
} elseif($t == 252 || $t == 253) {
$tn = 6; $n += 6; $noc += 2;
} else {
$n++;
}
if($noc >= $length) break;
}
if($noc > $length) $n -= $tn;
$strcut = substr($string, 0, $n);
}
else
{
$dotlen = strlen($dot);
$maxi = $length - $dotlen - 1;
for($i = 0; $i < $maxi; $i++)
{
$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
}
}
$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
return $strcut.$dot;
}

解决方案 »

  1.   

    php截取字符串函數
    substr
    以下是手冊的例子
    <?php
    echo substr('abcdef', 1);     // bcdef
    echo substr('abcdef', 1, 3);  // bcd
    echo substr('abcdef', 0, 4);  // abcd
    echo substr('abcdef', 0, 8);  // abcdef
    echo substr('abcdef', -1, 1); // f// Accessing single characters in a string
    // can also be achived using "curly braces"
    $string = 'abcdef';
    echo $string{0};                 // a
    echo $string{3};                 // d
    echo $string{strlen($string)-1}; // f?> 
      

  2.   

    没人知道吗?    主要是这个while 循环里面的.
      

  3.   

    while里是防止截取中文或其它特殊字符时时出现乱码错误,将字符转换成ASCII编码(ord)再判断的
      

  4.   

    恩,首先转成asc码,防止在截取中文的时候出现乱码的情况,主要是根据asc码的值来判断