PHP截取字符串cut_str_with_string 可以尝试一下

cut_str_with_string 截取字符串,可以指定要截取的字符串的长度,指定超过指定字符截取。

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* 截取中文英文字符串
* @param $str
* @param int $length 如果长度超过这个值,进行截取
* @param int $start
* @param int $end 如果不为零,设置为指定截取字符串的长度
* @param string $dot
* @return mixed|string
*/
function cut_str_with_string($str, $length=200, $start=0, $special_length=0, $dot='...')
{
$str = htmlspecialchars_decode($str);
$str = strip_tags($str);
$str = trim($str);
$str = preg_replace("/\s(?=\s)/","",$str);
$str = preg_replace("/[\n\r\t]/","",$str);
$str = preg_replace("/\s/","",$str);
$str = preg_replace("/ /","",$str);

$str = trim($str);

$strlen = mb_strlen($str);
$content = '';
$sing = 0;
$count = 0;

if($length > $strlen) {
return $str;
}
if($start >= $strlen) {
return '';
}

if($special_length){
if($length < $strlen && ($length > $special_length)){
while($special_length != ($count-$start)){
if(ord($str[$sing]) > 0xa0) {
if(!$start || $start <= $count) {
$content .= $str[$sing].$str[$sing+1].$str[$sing+2];
}
$sing += 3;
$count++;
}else{
if(!$start || $start <= $count) {
$content .= $str[$sing];
}
$sing++;
$count++;
}
}
}else{
return $str;
}
}else{
while($length != ($count-$start)){
if(ord($str[$sing]) > 0xa0) {
if(!$start || $start <= $count) {
$content .= $str[$sing].$str[$sing+1].$str[$sing+2];
}
$sing += 3;
$count++;
}else{
if(!$start || $start <= $count) {
$content .= $str[$sing];
}
$sing++;
$count++;
}
}
}
return $content.$dot;
}