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
<?php

class StringUtils
{
    /*
    public static function bytelen($data)
    {
        return strlen(bin2hex($data)) / 2;
    }
    */
    /// 前方一致
    public static function startsWith($haystack, $needles, $case = false)
    {
        $length = strlen($haystack);
        foreach ((array)$needles as $prefix) {
            $len = strlen($prefix);
            if (($len <= $length)
             && (substr_compare($haystack, $prefix, 0, $len, $case) === 0)
            ) {
                return true;
            }
        }
        return false;
    }
    // 後方一致
    public static function endsWith($haystack, $needles, $case = false)
    {
        $length = strlen($haystack);
        foreach ((array)$needles as $suffix) {
            $len = strlen($suffix);
            if (($len <= $length)
             && (substr_compare($haystack, $suffix, -$len, $len, $case) === 0)
            ) {
                return true;
            }
        }
        return false;
    }
    /// 部分一致
    public static function contains($haystack, $needles, $case = false)
    {
        $func = ($case ? 'stripos' : 'strpos');
        foreach ((array)$needles as $needle) {
            if ($func($haystack, $needle) !== false) {
                return true;
            }
        }
        return false;
    }
    // hash_equals polyfill
    // @see symfony/polyfill/polyfill/src/Php56/Php56.php <https://github.com/symfony/polyfill>
    //public static function equals($knownString, $userInput){}

    private function __construct()
    {
    }
}