Text::getUsernames()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 1
1
<?php
2
/**
3
 * Created for IG Monitoring.
4
 * User: jakim <[email protected]>
5
 * Date: 12.01.2018
6
 */
7
8
namespace jakim\ig;
9
10
11
class Text
12
{
13
14
    public static $usernamesPattern = '/(?:@)([A-Za-z0-9_](?:(?:[A-Za-z0-9_]|(?:\.(?!\.))){0,28}(?:[A-Za-z0-9_]))?)/i';
15
    public static $tagsPattern = '/(?:#)([\p{L}0-9_](?:(?:[\p{L}0-9_]){0,28}(?:[\p{L}0-9_]))?)/ui';
16
17
    /**
18
     * @param string $text
19
     * @param int $minLength
20
     * @return array|null
21
     *
22
     * @see http://blog.jstassen.com/2016/03/code-regex-for-instagram-username-and-hashtags/
23
     */
24
    public static function getTags(string $text, $minLength = 2): ?array
25
    {
26
        if (preg_match_all(static::$tagsPattern, mb_strtolower($text), $matches)) {
27
28
            $tags = array_filter($matches['1'], function ($tag) use ($minLength) {
29
                if ($minLength === false || is_int($minLength) && mb_strlen($tag) >= $minLength) {
30
                    return true;
31
                }
32
            });
33
34
            return array_values(array_unique($tags))?:null;
35
        }
36
37
        return null;
38
39
    }
40
41
    /**
42
     * @param string $text
43
     * @return array|null
44
     *
45
     * @see http://blog.jstassen.com/2016/03/code-regex-for-instagram-username-and-hashtags/
46
     */
47
    public static function getUsernames(string $text): ?array
48
    {
49
        if (preg_match_all(static::$usernamesPattern, mb_strtolower($text), $matches)) {
50
            return array_values(array_unique($matches['1']));
51
        }
52
53
        return null;
54
    }
55
}