會自動補充的字串截取函數

- 中國WEB開發者網絡 (http://www.webasp.net)
-- 技術教程 (http://www.webasp.net/article/)
--- 會自動補充的字串截取函數 (http://www.webasp.net/article/18/17004.htm)
-- 作者:未知
-- 發佈日期: 2005-03-15
會自動補充的字串截取函數


當截取句子時,可能會斷在一個單詞的中間,如beincity一詞被斷在了當中,這樣有時會不妥,下面這個函數就是用來解決這個問題的,當bDelete=TRUE時,就刪除那個被截斷的單詞(因為我覺得把它刪掉比把它補充完整要來得方便)。當然,這個函數支持對中文的操作,當雙字節字符被截斷時,會自動補充完整。

<?
function wordscut($string, $length, $bDelete=FALSE)
{
if(strlen($string) > $length) {
for($i = 0; $i < $length - 3; $i++) {
if(ord($string[$i]) > 127) {
$wordscut .= $string[$i].$string[$i + 1];
$i++;
} else {
$wordscut .= $string[$i];
}
}
///add
if( $i == $length-3 ) {
if( $bDelete ) {
if(ereg("[0-9a-zA-Z_\.\-]", $string[$i])) {
for($j=$i-1; $j>=0; $j--)
if(!ereg("[0-9a-zA-Z_\.\-]", $string[$j])) break;
$wordscut = substr($wordscut, 0, strlen($wordscut)-($i-$j)+1);
}
}
}
///
return $wordscut.' ...';
}
return $string;
}
echo wordscut("Hello,小堅.beincity!", 18, true);
echo "<br>";
echo wordscut("123 567 90abcde", 6+3, true);

?>

<?//another

function SubstrGB($in, $num, $delete=FALSE)
file://usage: $short = SubstrGB($yourText, $num, $delete?)
{
$pos=0;
$out="";
while($c = substr($in, $pos, 1)) {
if(ord($c) > 127) {
$out .= $c;
$pos++;
$c = substr($in, $pos, 1);
$out .= $c;
} else {
$out .= $c;
}
$pos++;
if($pos >= $num) break;
}
if($pos == $num) {
if( $delete ) {
if(ereg("[0-9a-zA-Z_\.\-]", substr($in, $pos, 1))) {
for($j = $pos-1; $j >= 0; $j--)
if(!ereg("[0-9a-zA-Z_\.\-]", substr($out, $j, 1)))
break;
$out = substr($out, 0, strlen($out)-($pos-$j)+1);
}
}
}
return $out;
}

?>

責任編輯: microrain



webasp.net