ThinkPHP 3.1.3 seems to have no built-in method to intercept Chinese strings. I searched for a long time and couldn’t find it. Below, the author has added a function to intercept Chinese strings. The specific code is as follows. Friends in need can refer to it. Down.
The following code is added to the common.php file in the Common directory of the directory where the project is located. For example, the author's is the www/Common/common.php file. Of course, you can also add it directly to the Common/common.php file of thinkphp. inside so that all items are available.
function truncate_cn($string,$length=0,$ellipsis='…',$start=0){ $string=strip_tags($string); $string=preg_replace('/\n/is','',$string); //$string=preg_replace('/ | /is','',$string);//清除字符串中的空格 $string=preg_replace('/ /is','',$string); preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/",$string,$string); if(is_array($string)&&!empty($string[0])){ $string=implode('',$string[0]); if(strlen($string)<$start+1){ return ''; } preg_match_all("/./su",$string,$ar); $string2=''; $tstr=''; //www.phpernote.com for($i=0;isset($ar[0][$i]);$i++){ if(strlen($tstr)<$start){ $tstr.=$ar[0][$i]; }else{ if(strlen($string2)<$length+strlen($ar[0][$i])){ $string2.=$ar[0][$i]; }else{ break; } } } return $string==$string2?$string2:$string2.$ellipsis; }else{ $string=''; } return $string; }
is used in thinkphp templates as follows:
{$info.subject|truncate_cn=40,'',0}
means to intercept the $info['subject'] string. Starting from the 0th string, intercept the string with a length of 40. If the length of the intercepted string is less than the length of the original string, nothing will be displayed. The default is..., in fact, the last two parameters are optional.