|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @author Kevin Bond <[email protected]> |
|
4
|
|
|
*/ |
|
5
|
|
|
namespace zenstruck\string; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Replaces " " with a single space and converts multiple sequential spaces into a single space. |
|
9
|
|
|
* |
|
10
|
|
|
* @param string $str |
|
11
|
|
|
* |
|
12
|
|
|
* @return string |
|
13
|
|
|
*/ |
|
14
|
|
|
function remove_whitespace($str) |
|
15
|
|
|
{ |
|
16
|
|
|
return preg_replace('/\s+/', ' ', str_replace(' ', ' ', $str)); |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Similar to core "trim" but returns null instead of an empty string |
|
21
|
|
|
* When an array is passed, all elements get processed recursively. |
|
22
|
|
|
* |
|
23
|
|
|
* @param string|array $data |
|
24
|
|
|
* @param null|string $character_mask |
|
25
|
|
|
* |
|
26
|
|
|
* @return array|null|string |
|
27
|
|
|
*/ |
|
28
|
|
|
function null_trim($data, $character_mask = null) |
|
29
|
|
|
{ |
|
30
|
|
|
if (is_array($data)) { |
|
31
|
|
|
return array_map( |
|
32
|
|
|
function ($value) use ($character_mask) { |
|
33
|
|
|
return null_trim($value, $character_mask); |
|
34
|
|
|
}, |
|
35
|
|
|
$data |
|
36
|
|
|
); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
$trimmedValue = null === $character_mask ? trim($data) : trim($data, $character_mask); |
|
40
|
|
|
|
|
41
|
|
|
if ($trimmedValue === '') { |
|
42
|
|
|
return null; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
return $trimmedValue; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* Truncates text to a length without breaking words. |
|
50
|
|
|
* |
|
51
|
|
|
* @param string $str |
|
52
|
|
|
* @param int $length |
|
53
|
|
|
* @param string $suffix |
|
54
|
|
|
* |
|
55
|
|
|
* @return string |
|
56
|
|
|
*/ |
|
57
|
|
|
function truncate_word($str, $length = 255, $suffix = '...') |
|
58
|
|
|
{ |
|
59
|
|
|
$output = remove_whitespace(trim($str)); |
|
60
|
|
|
|
|
61
|
|
|
if (strlen($output) > $length) { |
|
62
|
|
|
$output = wordwrap($output, $length - strlen($suffix)); |
|
63
|
|
|
$output = substr($output, 0, strpos($output, "\n")); |
|
64
|
|
|
$output .= $suffix; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
return strlen($output) > $length ? '' : $output; |
|
68
|
|
|
} |
|
69
|
|
|
|