/
text_helper.php
362 lines (332 loc) · 11.5 KB
/
text_helper.php
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
<?php
/**
* This module provides methods for cycling iteration inside views.
*
* @ingroup helperclass
*/
class Cycle {
/**
* Build the class with the specified values.
*
* @param mixed $values
* Data through which class will cycle.
*/
function __construct($values) {
$this->values = $values;
$this->index = 0;
}
/**
* Returns values.
*
* @return mixed
* The values stored in the $this->values class variable.
*/
function values() {
return $this->values;
}
/**
* Reset the cycle index.
*/
function reset() {
$this->index = 0;
}
/**
* Returns the current value in iteration.
*
* @return mixed
* The current data in the iteration.
*/
function current_value() {
return $this->values[$this->index];
}
/**
* Returns the current value and iterate to the next value.
*
* @return mixed
* The current data in the iteration.
*/
function value() {
$value = $this->current_value();
$this->next();
return $value;
}
/**
* Goes to the next value in the iteration.
*/
function next() {
$this->index = ($this->index + 1) % count($this->values);
}
}
/**
* This module provides methods for text handling.
*
* @ingroup helperclass
*/
class TextHelper {
private static $cycles = array();
/**
* Attempts to pluralize the specified text.
*
* @param string $string
* The string to be pluralized.
*
* @return mixed
* The current data in the iteration.
*
* @ingroup helperfunc
*/
function pluralize($string) {
$plural = array(
array('/(quiz)$/i', "$1zes" ),
array('/^(ox)$/i', "$1en" ),
array('/([m|l])ouse$/i', "$1ice" ),
array('/(matr|vert|ind)ix|ex$/i', "$1ices" ),
array('/(x|ch|ss|sh)$/i', "$1es" ),
array('/([^aeiouy]|qu)y$/i', "$1ies" ),
array('/([^aeiouy]|qu)ies$/i', "$1y" ),
array('/(hive)$/i', "$1s" ),
array('/(?:([^f])fe|([lr])f)$/i', "$1$2ves"),
array('/sis$/i', "ses" ),
array('/([ti])um$/i', "$1a" ),
array('/(buffal|tomat)o$/i', "$1oes" ),
array('/(bu)s$/i', "$1ses" ),
array('/(alias|status)$/i', "$1es" ),
array('/(octop|vir)us$/i', "$1i" ),
array('/(ax|test)is$/i', "$1es" ),
array('/s$/i', "s" ),
array('/$/', "s" )
);
$irregular = array(
array('move', 'moves' ),
array('sex', 'sexes' ),
array('child', 'children'),
array('man', 'men' ),
array('person', 'people' )
);
$uncountable = array(
'sheep',
'fish',
'series',
'species',
'money',
'rice',
'information',
'equipment'
);
// save some time in the case that singular and plural are the same
if (in_array(strtolower($string), $uncountable))
return $string;
// check for irregular singular forms
foreach ($irregular as $noun) {
if (strtolower($string) == $noun[0])
return $noun[1];
}
// check for matches using regular expressions
foreach ($plural as $pattern) {
if (preg_match($pattern[0], $string))
return preg_replace($pattern[0], $pattern[1], $string);
}
return $string;
}
/**
* Creates a Cycle object whose cycles through elements of an array every time it is called. This can be used for example, to alternate classes for table rows. You can use named cycles to allow nesting in loops. Passing an Array as the last parameter with a 'name' key will create a named cycle. The default name for a cycle without a 'name' key is "default". You can manually reset a cycle by calling #reset_cycle and passing the name of the cycle.
* @param mixed "$string, $string, array('name' => $name)" Array is optional. $string are the element through it will cycle
* @return string Return current value of the cycle
*/
function cycle() {
$values = func_get_args();
if (is_array($values[count($values)-1])) {
$options = array_pop($values);
}
$name = isset($options["name"]) ? $options["name"] : "default";
if (!isset(self::$cycles[$name]) || self::$cycles[$name]->values() != $values) {
self::$cycles[$name] = new Cycle($values);
}
$cycle = self::$cycles[$name];
return $cycle->value();
}
/**
* Reset the cycle pointer.
*
* @param string $name (optional)
* The specified name of the cycle to reset.
*
* @ingroup helperfunc
*/
function reset_cycle($name = "default") {
if (isset(self::$cycles[$name])) {
self::$cycles[$name]->reset();
}
}
/**
* Truncate the text to the specified length.
*
* @param string $text
* The text to be truncated.
* @param array $options (optional)
* An array with options to be passed to the function.
* Available options:
* - length (default 30): the length at which truncate the text
* - omission (default '...'): the suffix string to be added to the
* truncate text
* - word_count (default FALSE): if is TRUE the lenght value count words
* else if is FALSE count chars
* - separator (default FALSE): the separator string used to trim the
* argument
* - html (default FALSE): set if you want to preserve html in string.
* If is set to false remove ALL HTML tags.
* - allowed_tags (default array('b', 'i', 'em', 'strong')): if html is TRUE preserve
* the allowed tags. If this param is set to 'all' leave untouched the string.
*
* @return string
* The truncated text.
*
* @ingroup helperfunc
*/
function truncate($text, $options = array()) {
$options = array_merge(
array(
'length' => 30,
'omission' => '...',
'word_count' => FALSE,
'separator' => FALSE,
'html' => FALSE,
'allowed_tags' => array('b', 'i', 'em', 'strong')
),
$options
);
if (!$options['html']){
// if html is false strip all html tags
$text = strip_tags($text);
} elseif ($options['html']){
if ($options['allowed_tags'] != 'all'){
// if the allowed_tags are not 'all' remove all tags leaving the allowed
$text = strip_tags($text, "<". implode("><", $options['allowed_tags']) .">");
}
}
// start to count words
if ($options['word_count']){
// split string into words
$words = explode(" ", $text);
$counter = 0;
$text = "";
foreach ($words as $word) {
if ($counter >= ($options['length'])){
// leave foreach if reached the limit
break;
} else {
// add words to result string
$text .= $word ." ";
// if the word is a HTML tag don't count it
if ((mb_substr($word, 0, 1) != "<") || (mb_substr($word, -1) != ">")){
$counter++;
}
}
}
// if the last substring of $text is separator remove it
if (mb_substr($text, -strlen($options['separator'])) === $options['separator']){
$text = mb_substr($text, 0, (strlen($text) - strlen($options['separator'])));
}
if (count($words) >= $options['length']){
$text = $text . $options['omission'];
}
if ($options['html']){
$actual_error_reporting_level = error_reporting();
error_reporting(0);
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'. "<wrapper>{$text}</wrapper>");
error_reporting($actual_error_reporting_level);
libxml_clear_errors();
$text = preg_replace('~<(?:!DOCTYPE|/?(?:html|body|head|meta|wrapper))[^>]*>\s*~i', '', $doc->saveHTML());
}
return $text;
}
// or chars
else{
$length_with_room_for_omission = $options['length'] - strlen($options['omission']);
if ($options['separator']) {
$stop = FALSE;
for ($i = 0; $i <= min(strlen($text), $length_with_room_for_omission); $i++) {
if (mb_substr($text, $i, strlen($options['separator'])) == $options['separator']) {
$stop = $i;
}
}
if ($stop === FALSE) {
$stop = $length_with_room_for_omission;
}
}
else {
$stop = $length_with_room_for_omission;
}
if (strlen($text) > $options['length']) {
return mb_substr($text, 0, $stop) . $options['omission'];
}
else {
return $text;
}
}
}
/**
* Run a check against $check and returns 'active' or 'inactive' string accordingly
* @param mixed $check This check will be tested against truthness. Could be anything
* @param string $active (optional) Text to print when $check is true. Dafault: 'active'
* @param string $inactive (optional) Text to print when $check is false. Default: 'inactive'
* @return string $active or $inactive accordingly
*/
function active_if($check, $active = "active", $inactive = "inactive") {
return $check ? $active : $inactive;
}
/**
* Returns a string with the first character of each word capitalized.
*
* @param string $text
* The text to be capitalized.
*
* @return string
* The capitalized text.
*
* @ingroup helperfunc
*/
function capitalize($text) {
return ucfirst(strtolower($text));
}
/**
* Capitalizes the first letter of every word.
*
* @param string $text
* The text to be capitalized.
*
* @return string
* The text with every word capitalized.
*
* @ingroup helperfunc
*/
function titleize($text) {
$words = explode(" ", $text);
$capitalized_words = array();
foreach ($words as $word) {
$capitalized_words[] = capitalize($word);
}
return join(" ", $capitalized_words);
}
/**
* Check if the string passed as parameter is a valid URL.
*
* NO SANITAZE IS PERFORMED on the URL! URL like this:
* http://example.com/"><script>alert(document.cookie)</script>
* DO PASS validation (syntactically are valid URLs).
*
* @param string $url
* A URL to be validated.
*
* @return bool
* Return TRUE if the URL is valid, FALSE otherwise.
*
* @ingroup helperfunc
*/
function is_valid_url($url) {
return (bool)filter_var($url, FILTER_VALIDATE_URL);
}
}
Wordless::register_helper("TextHelper");