, http://linuxchannel.net
##
## [changes]
## - 2005.01.04, bug fixed
## - 2002.11.22, add check_tag()
## - 2002.10.04
##
## [download]
## - http://ftp.linuxchannel.net/devel/php_strcut/
##
## [demo]
## - http://linuxchannel.net/gaggle/strcut.php
##
## [usage]
## $strcut = new strcut;
## echo $strcut->cut('string...string',10);
##
class strcut
{
## reference : http://jsboard.kldp.org/
##
function unhtmlspecialchars($str)
{
$tr = array_flip(get_html_translation_table(HTML_SPECIALCHARS));
$str = preg_replace(array('/'/','/&/','/&(nbsp;|#032)/'),array("'",'&',' '),$str);
$str = strtr($str,$tr);
return $str;
}
## source : http://jsboard.kldp.org/
##
## arguments :
## $str : string, target string
## $html : boolean, if $str included HTML TAG, then set to 1
##
function ugly_han($str, $html=0)
{
if(!$html) return preg_replace('/&(#|amp)/','&\\1',$str);
else return str_replace('&','&',$str);
}
function check_tag($str)
{
## type1 : ,
,
, etc ugly TAG
##
if(preg_match(';<[^>]*$;',$str))
{
$str = preg_replace(';<[^>]*$;','',$str);
//$type = ' _1'; // debugging
}
## type2 : aaaaa,
dddddd## if(!preg_match(';<([A-Z]+)[^>]*>.*\\1>.*$;i',$str)) { $from = array(';]*)>(.*)$;i',';<;',';<[^>]*$;'); $to = array('','<\\1\\2>\\3\\1>','',''); $str = preg_replace($from,$to,$str); //$type .= ' _2'; // debugging } return $str . $type; } ## reference : http://www.phpschool.com/bbs2/inc_view.html?id=6167&code=tnt2 ## ## arguments : ## $str string, target string ## $len integer, want to cutting length ## $html boolean, default 0, if $str included HTML TAG, then set to 1 ## $ugly boolean, default 0, if checked ugly_han(), then set to 1 ## ## return : ## $str string, cutted string ## function cut($str, $len, $html=0, $ugly=0, $suffix='') { if(strlen($str) <= $len) return $str; if(!$ugly) $str = $this ? $this->ugly_han($str,$html) : strcut::ugly_han($str,$html); if(!$html) $str = $this ? $this->unhtmlspecialchars($str) : strcut::unhtmlspecialchars($str); $i = $len - 1; while(ord($str[$i]) & 0x80) $i--; $fix = $len - (($len + $i + 1) & 1); $cutted = substr($str, 0, $fix); ## good idea, but bad speed ## //if($str[$fix-1].$str[$fix] == '') $str = preg_replace('/&[^&]*$/','',$cutted); //else $str = preg_replace('/[0-9]*$/','',$cutted); $str = preg_replace('/([0-9]*|&)$/','',$cutted); if($html) $str = $this ? $this->check_tag($str) : strcut::check_tag($str); else { $str = htmlspecialchars($str); $str = str_replace('&','&',$str); } return $str.$suffix; } } // end of strcut class ?>