-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtruncate.php
More file actions
62 lines (60 loc) · 1.83 KB
/
truncate.php
File metadata and controls
62 lines (60 loc) · 1.83 KB
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
<?php
// Written by Phil Banks
// Based on code from http://www.the-art-of-web.com/php/truncate/
//// Original PHP code by Chirp Internet: www.chirp.com.au. Please acknowledge use of this code by including this header.
function truncate($type='words', $string, $length, $break='.', $pad='')
{
switch($type) {
case 'words':
switch($break) {
// Split at the next end of a sentence PAST the $length.
case '.':
$output = strtok($string, " \n");
while(--$length > 0) $output .= " " . strtok(" \n");
if (substr($output, -1) !== '.') $output .= " " . strtok(".\n") . ".";
return $output;
break;
// Split at the next end of a word PAST the $length.
case ' ':
$output = strtok($string, " \n");
while(--$length > 0) $output .= " " . strtok(" \n");
if($output != $string) $output .= $pad;
return $output;
break;
}
break;
case 'chars':
switch($break) {
// Split at the next end of a sentence PAST the $length.
case '.':
if(strlen($string) <= $length) return $string;
if(false !== ($breakpoint = strpos($string, $break, $length))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . ". " . $pad;
}
}
return $string;
break;
// Split at the next end of a word PAST the $length.
case ' ':
if(strlen($string) <= $length) return $string;
if(false !== ($breakpoint = strpos($string, $break, $length))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $string;
break;
// Split at the next character PAST the $length.
case '*':
if(strlen($string) <= $length) return $string;
else {
$string = substr($string, 0, $length) . $pad;
}
return $string;
break;
}
break;
}
}
?>