string.php ➔ remove_whitespace()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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