Completed
Pull Request — master (#20)
by
unknown
03:12
created

Text::removeUsernameFormattation()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 32
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 10
nc 2
nop 2
1
<?php
2
3
namespace PhpBotFramework\Entities;
4
5
/**
6
 * \class Text
7
 * \brief Contains text helper methods
8
 */
9
class Text {
10
11
    /**
12
     * \addtogroup Utility-methods Utility methods
13
     * \brief Helper methods.
14
     * @{
15
     */
16
17
    /**
18
     * \brief Get hashtag contained in a string.
19
     * \details Check hashtags in a string using regex.
20
     * All valid hashtags will be returned in an array.
21
     * [Credis to trante](http://stackoverflow.com/questions/3060601/retrieve-all-hashtags-from-a-tweet-in-a-php-function).
22
     * @param $string The string to check for hashtags.
23
     * @return An array of valid hashtags, can be empty.
24
     */
25
    public static function getHashtags(string $string) : array {
26
27
        // Use regex to check
28
        if (preg_match_all("/(#\w+)/u", $string, $matches) != 0) {
29
30
            $hashtagsArray = array_count_values($matches[0]);
31
32
            $hashtags = array_keys($hashtagsArray);
33
34
        }
35
36
        // Return an array of hashtags
37
        return $hashtags ?? [];
38
    }
39
40
    /**
41
     * \brief Remove html formattation from telegram usernames in string.
42
     * \details Remove the $modificator html formattation from a message containing telegram username, to let the user click them.
43
     * @param $string to parse.
44
     * @param $tag Formattation tag to remove.
45
     * @return The string, modified if there are usernames. Otherwise $string.
46
     */
47
    public static function removeUsernameFormattation(string $string, string $tag) : string {
48
49
        // Check if there are usernames in string using regex
50
        if (preg_match_all('/(@\w+)/u', $string, $matches) != 0) {
51
52
            $usernamesArray = array_count_values($matches[0]);
53
54
            $usernames = array_keys($usernamesArray);
55
56
            // Count how many username we've got
57
            $count = count($usernames);
58
59
            // Delimitator to make the formattation start
60
            $delimitator_start = '<' . $tag . '>';
61
62
            // and to make it end
63
            $delimitator_end = '</' . $tag . '>';
64
65
            // For each username
66
            for ($i = 0; $i !== $count; $i++) {
67
68
                // Put the Delimitator_end before the username and the start one after it
69
                $string = str_replace($usernames[$i], $delimitator_end . $usernames[$i] . $delimitator_start, $string);
70
71
            }
72
73
        }
74
75
        // Return the string, modified or not
76
        return $string;
77
78
    }
79
80
}
81