1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* |
4
|
|
|
* Topic Preview |
5
|
|
|
* |
6
|
|
|
* @copyright (c) 2014 Matt Friedman |
7
|
|
|
* @license GNU General Public License, version 2 (GPL-2.0) |
8
|
|
|
* |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace vse\topicpreview\core\trim; |
12
|
|
|
|
13
|
|
|
class trim |
14
|
|
|
{ |
15
|
|
|
/** @var array Array of trim tools */ |
16
|
|
|
protected $tools; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Constructor |
20
|
|
|
* |
21
|
|
|
* @param manager $manager Trim tools manager object |
22
|
|
|
*/ |
23
|
36 |
|
public function __construct(manager $manager) |
24
|
|
|
{ |
25
|
36 |
|
$this->tools = $manager->get_tools(); |
26
|
36 |
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Trim and clean text |
30
|
|
|
* |
31
|
|
|
* @param string $message Message text |
32
|
|
|
* @param int $length The length to trim text to |
33
|
|
|
* |
34
|
|
|
* @return string Trimmed message text |
35
|
|
|
*/ |
36
|
28 |
|
public function trim_text($message, $length) |
37
|
|
|
{ |
38
|
|
|
// display smileys as text :) |
39
|
28 |
|
$message = smiley_text($message, true); |
|
|
|
|
40
|
|
|
|
41
|
|
|
/** @var tools\tool_interface $tool Run text through trim tools to strip out bbcodes and other markup */ |
42
|
28 |
|
foreach ($this->tools as $tool) |
43
|
|
|
{ |
44
|
28 |
|
$message = $tool->set_text($message)->run(); |
45
|
28 |
|
} |
46
|
|
|
|
47
|
28 |
|
if (utf8_strlen($message) <= $length) |
|
|
|
|
48
|
28 |
|
{ |
49
|
24 |
|
return $this->tp_nl2br($message); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
// trim the text to the last whitespace character before the cut-off |
53
|
6 |
|
$message = preg_replace('/\s+?(\S+)?$/', '', utf8_substr($message, 0, $length)); |
|
|
|
|
54
|
|
|
|
55
|
6 |
|
return $this->tp_nl2br($message) . '...'; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Convert and preserve line breaks |
60
|
|
|
* http://stackoverflow.com/questions/816085/removing-redundant-line-breaks-with-regular-expressions |
61
|
|
|
* |
62
|
|
|
* @param string $message Message text |
63
|
|
|
* |
64
|
|
|
* @return string Message text with line breaks |
65
|
|
|
*/ |
66
|
28 |
|
protected function tp_nl2br($message) |
67
|
|
|
{ |
68
|
28 |
|
return nl2br(preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/', "\n\n", $message)); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|