做网站程序的开发,不得不遇到的就是截取字符串,而截取中文字符是肯定要遇到的,比如截取文章的标题,摘要,等等,虽然这些也可以通过css来操作,但是,我们也不得不学会这个功能,因为有的时候,可能并不是统一的进行截取,单独使用的时候需要用到。截取中文字符的原理其实我之前也有说过,就是给他一个截取的总长度,我们可以一个字符为单位来截取,在保证总截取不超过限制长度的情况下判读是否成功截取,成功就继续,不成功就代表可能为中文,就跳过截取两个字符。或utf8的三个字符。以此类推。这里我总结了两个截取中文的方法。
第一种是定义了一个方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?PHP public static function msubstr($str, $length, $start = 0, $charset = "utf-8", $suffix = true) { if (function_exists("mb_substr")) return mb_substr($str, $start, $length, $charset); elseif (function_exists('iconv_substr')) { return iconv_substr($str, $start, $length, $charset); } $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; preg_match_all($re[$charset], $str, $match); $slice = join("", array_slice($match[0], $start, $length)); if ($suffix) return $slice . "…"; return $slice; } |
第二种
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?PHP $str="这个字符好长呀,^_^"; $Short_Str=showShort($str,4);//截取前面4个汉字,结果为:这个字符... Echo "$Short_Str"; Function showShort($str,$len) { $tempstr = csubstr($str,0,$len); if ($str<>$tempstr) $tempstr .= "..."; //要以什么结尾,修改这里就可以. return $tempstr; } Function csubstr($str,$start,$len) { $strlen=strlen($str); $clen=0; for($i=0;$i<$strlen;$i++,$clen++) { if ($clen>=$start+$len) break; if(ord(substr($str,$i,1))>0xa0) { if ($clen>=$start) @$tmpstr.=substr($str,$i,2); $i++; } else { if ($clen>=$start) $tmpstr.=substr($str,$i,1); } } return $tmpstr; } |
本文链接:http://www.521php.com/archives/159/
程序本天成,妙手偶得之!我们只是代码的搬运工!
转载请注明:http://www.521php.com/archives/159/