php专区

 首页 > php专区 > PHP应用 > 常用功能 > 9、PHP截取字符串长度

9、PHP截取字符串长度

分享到:
【字体:
导读:
          我们经常会遇到需要截取字符串(含中文汉字)长度的情况,比如标题显示不能超过多少字符,超出的长度用表示,以下函数可以满足你的需求。 1 /* 2 3 Utf-8、gb2312都支持的汉字截取函数...

我们经常会遇到需要截取字符串(含中文汉字)长度的情况,比如标题显示不能超过多少字符,超出的长度用…表示,以下函数可以满足你的需求。

复制代码
 1 /* 
 2 
 3  Utf-8、gb2312都支持的汉字截取函数 
 4 
 5  cut_str(字符串, 截取长度, 开始长度, 编码); 
 6 
 7  编码默认为 utf-8 
 8 
 9  开始长度默认为 0 
10 
11 */ 
12 
13 function cutStr($string, $sublen, $start = 0, $code = 'UTF-8'){ 
14 
15     if($code == 'UTF-8'){ 
16 
17         $pa = "/[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]/"; 
18 
19         preg_match_all($pa, $string, $t_string); 
20 
21  
22 
23         if(count($t_string[0]) - $start > $sublen) return join('', array_slice
24 ($t_string[0], $start, $sublen))."..."; 
25 
26         return join('', array_slice($t_string[0], $start, $sublen)); 
27 
28     }else{ 
29 
30         $start = $start*2; 
31 
32         $sublen = $sublen*2; 
33 
34         $strlen = strlen($string); 
35 
36         $tmpstr = ''; 
37 
38  
39 
40         for($i=0; $i<$strlen; $i++){ 
41 
42             if($i>=$start && $i<($start+$sublen)){ 
43 
44                 if(ord(substr($string, $i, 1))>129){ 
45 
46                     $tmpstr.= substr($string, $i, 2); 
47 
48                 }else{ 
49 
50                     $tmpstr.= substr($string, $i, 1); 
51 
52                 } 
53 
54             } 
55 
56             if(ord(substr($string, $i, 1))>129) $i++; 
57 
58         } 
59 
60         if(strlen($tmpstr)<$strlen ) $tmpstr.= "..."; 
61 
62         return $tmpstr; 
63 
64     } 
65 
66 }
67 
68 //使用方法如下
69 
70 $str = "jQuery插件实现的加载图片和页面效果"; 
71 
72 echo cutStr($str,16);
复制代码

分享到:
8、PHP强制下载文件
有时我们不想让浏览器直接打开文件,如PDF文件,而是要直接下载文件,那么以下函数可以强制下载文件,函数中使用了application/octet-stream头类型。 1 function download($filename){ 2 3 if ((isset($filename))&&(file_exists($filename))){ 4 5 header("Content-length: ".files...
10、PHP获取客户端真实IP
我们经常要用数据库记录用户的IP,以下代码可以获取客户端真实的IP: 1 //获取用户真实IP 2 3 function getIp() { 4 5 if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), 6 "unknown")) 7 8 $ip = getenv("HTTP_CLIENT_IP"); 9 10 else 1...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……