Passed
Push — master ( c304ca...2a9eb0 )
by Lars
03:47
created

UTF8   F

Complexity

Total Complexity 1688

Size/Duplication

Total Lines 12720
Duplicated Lines 0 %

Test Coverage

Coverage 80.06%

Importance

Changes 93
Bugs 51 Features 5
Metric Value
eloc 4321
c 93
b 51
f 5
dl 0
loc 12720
ccs 3055
cts 3816
cp 0.8006
rs 0.8
wmc 1688

299 Methods

Rating   Name   Duplication   Size   Complexity  
A add_bom_to_string() 0 7 2
A __construct() 0 2 1
A access() 0 11 4
A str_substr_after_first_separator() 0 28 6
A str_surround() 0 3 1
A strip_whitespace() 0 7 2
A strnatcasecmp() 0 5 1
A strncasecmp() 0 10 1
A strnatcmp() 0 9 2
A strpbrk() 0 11 4
A chr_to_decimal() 0 30 6
A array_change_key_case() 0 23 5
D chr() 0 101 18
B between() 0 48 8
A chr_map() 0 5 1
A char_at() 0 7 2
A chars() 0 3 1
A chr_size_list() 0 17 3
A checkForSupport() 0 47 4
A chr_to_hex() 0 11 3
A callback() 0 3 1
A binary_to_str() 0 12 3
A bom() 0 3 1
A file_has_bom() 0 8 2
A str_begins() 0 3 1
A max() 0 14 3
B str_camelize() 0 70 10
A parse_str() 0 16 4
A filter_input() 0 13 2
A str_contains() 0 10 2
B str_to_lines() 0 29 8
A substr_in_byte() 0 18 6
A get_unique_string() 0 15 2
A is_bom() 0 10 3
A is_hexadecimal() 0 8 2
A encode_mimeheader() 0 25 5
A substr_left() 0 15 4
A count_chars() 0 11 1
D strlen() 0 99 19
A html_entity_decode_helper() 0 18 3
A str_isubstr_last() 0 25 4
A ctype_loaded() 0 3 1
A str_replace_beginning() 0 24 6
A has_uppercase() 0 8 2
A remove_left() 0 24 4
B stripos() 0 59 11
A str_offset_exists() 0 10 2
D strrchr() 0 101 20
A to_filename() 0 9 1
A str_iends_with() 0 11 3
A max_chr_width() 0 8 2
A isBinary() 0 3 1
C utf8_decode() 0 61 13
A ltrim() 0 19 4
A emoji_decode() 0 18 2
A is_utf8() 0 13 4
A remove_html() 0 3 1
B str_longest_common_suffix() 0 54 10
C wordwrap() 0 68 14
B ucfirst() 0 57 7
A lcword() 0 13 1
A str_pad_both() 0 12 1
A str_index_last() 0 11 1
A str_substr_last() 0 33 6
A mbstring_loaded() 0 3 1
A str_limit() 0 26 6
A html_escape() 0 6 1
A toUTF8() 0 3 1
A string() 0 10 1
C normalize_encoding() 0 134 14
B rxClass() 0 39 8
B get_file_type() 0 61 7
A str_ensure_right() 0 13 4
A chr_to_int() 0 3 1
B str_titleize_for_humans() 0 155 5
C is_utf16() 0 65 16
A isHtml() 0 3 1
C filter() 0 59 13
A normalize_whitespace() 0 9 1
A str_starts_with() 0 11 3
A isBase64() 0 3 1
A str_humanize() 0 15 1
A is_html() 0 14 2
A decode_mimeheader() 0 15 5
C substr_count_in_byte() 0 55 15
A html_decode() 0 6 1
A strchr() 0 13 1
A strichr() 0 13 1
A isUtf32() 0 3 1
A str_index_first() 0 11 1
A strlen_in_byte() 0 12 3
A str_ireplace_ending() 0 21 6
A rtrim() 0 19 4
C str_longest_common_substring() 0 76 16
A regex_replace() 0 20 3
A chunk_split() 0 3 1
A titlecase() 0 31 5
A getData() 0 6 1
A str_iindex_first() 0 11 1
B strtolower() 0 54 10
B urldecode() 0 37 8
A str_isubstr_before_first_separator() 0 19 5
B strrev() 0 43 10
A replace_all() 0 11 2
D substr_replace() 0 124 27
A removeBOM() 0 3 1
A strstr_in_byte() 0 15 4
A emoji_encode() 0 18 2
A str_matches_pattern() 0 3 1
A is_alpha() 0 8 2
C str_titleize() 0 69 12
A ws() 0 3 1
B get_random_string() 0 56 10
A str_replace_first() 0 20 2
A fix_utf8() 0 30 4
A toLatin1() 0 3 1
A str_pad_right() 0 12 1
B ucwords() 0 48 9
A first_char() 0 14 4
A to_boolean() 0 35 5
C stristr() 0 68 15
A isUtf8() 0 3 1
B strwidth() 0 43 8
A str_iends() 0 3 1
A css_stripe_media_queries() 0 6 1
A trim() 0 19 4
A clean() 0 47 6
A is_serialized() 0 11 3
A str_upper_camelize() 0 8 1
A is_uppercase() 0 8 2
A substr_compare() 0 33 6
C substr_count() 0 62 16
D str_pad() 0 146 16
A urldecode_unicode_helper() 0 8 2
A str_ireplace() 0 18 3
A to_latin1() 0 3 1
A str_replace_ending() 0 24 6
A string_has_bom() 0 10 3
B strtr() 0 34 8
A str_contains_all() 0 23 6
A is_ascii() 0 3 1
A normalize_line_ending() 0 3 1
A str_isubstr_after_last_separator() 0 26 5
D range() 0 65 23
B strspn() 0 30 10
A strcasecmp() 0 21 1
A str_transliterate() 0 6 1
B rawurldecode() 0 37 8
A str_ends() 0 3 1
B str_capitalize_name_helper() 0 79 10
A utf8_encode() 0 16 3
A normalize_msword() 0 3 1
C str_detect_encoding() 0 111 13
A spaces_to_tabs() 0 11 3
A str_istarts_with() 0 11 3
A is_blank() 0 8 2
A str_replace() 0 14 1
A substr_iright() 0 15 4
D getCharDirection() 0 105 118
A htmlspecialchars() 0 15 3
A replace() 0 11 2
A filter_var_array() 0 12 2
A decimal_to_chr() 0 3 1
A to_iso8859() 0 16 4
A words_limit() 0 20 5
A strip_tags() 0 18 4
A pcre_utf8_support() 0 4 1
A str_isubstr_before_last_separator() 0 24 6
D str_truncate_safe() 0 78 18
A codepoints() 0 29 4
A substr_right() 0 31 6
A lowerCaseFirst() 0 13 1
D str_split() 0 125 28
A str_ends_with_any() 0 13 4
A strrpos_in_byte() 0 12 4
A cleanup() 0 25 2
A remove_right() 0 25 4
F strrpos() 0 119 25
A remove_html_breaks() 0 3 1
A showSupport() 0 8 2
A remove_invisible_characters() 0 9 1
A single_chr_html_encode() 0 18 4
A str_replace_last() 0 19 2
A str_iindex_last() 0 11 1
A str_substr_before_last_separator() 0 31 6
B is_binary() 0 35 9
A intlChar_loaded() 0 3 1
B strtocasefold() 0 33 7
A lcfirst() 0 44 5
A tabs_to_spaces() 0 11 3
A finfo_loaded() 0 3 1
B str_truncate() 0 44 7
D strripos() 0 96 19
A strpos_in_byte() 0 12 4
A str_ends_with() 0 11 3
A fits_inside() 0 3 1
A to_ascii() 0 6 1
A is_binary_file() 0 16 3
A intl_loaded() 0 3 1
A reduce_string_array() 0 29 6
B str_longest_common_prefix() 0 51 8
A mbstring_overloaded() 0 11 2
A str_pad_left() 0 12 1
A str_substr_first() 0 33 6
A html_stripe_empty_tags() 0 6 1
A remove_bom() 0 22 5
A str_repeat() 0 5 1
A whitespace_table() 0 3 1
A substr_count_simple() 0 31 6
A str_iends_with_any() 0 13 4
A str_substr_after_last_separator() 0 28 6
A str_isubstr_after_first_separator() 0 26 5
F extract_text() 0 175 34
A json_loaded() 0 3 1
A isBom() 0 3 1
B str_snakeize() 0 55 6
A int_to_chr() 0 3 1
A is_lowercase() 0 8 2
A str_sort() 0 15 3
D to_utf8() 0 117 35
A ucword() 0 6 1
A str_underscored() 0 3 1
A str_offset_get() 0 14 4
A hasBom() 0 3 1
A toAscii() 0 6 1
A str_ibegins() 0 3 1
A str_capitalize_name() 0 8 1
B str_limit_after_word() 0 55 11
A iconv_loaded() 0 3 1
A lcwords() 0 31 6
A str_upper_first() 0 13 1
A isAscii() 0 3 1
A normalizeEncoding() 0 3 1
A swapCase() 0 17 4
A filter_var() 0 12 2
A substr_ileft() 0 15 4
A is_empty() 0 3 1
B html_encode() 0 53 11
A str_dasherize() 0 3 1
A isUtf16() 0 3 1
A str_ensure_left() 0 11 3
F encode() 0 140 37
B urldecode_fix_win1252_chars() 0 227 1
A toIso8859() 0 3 1
C is_utf32() 0 65 16
C ord() 0 72 16
A is_alphanumeric() 0 8 2
A strtonatfold() 0 7 1
A json_decode() 0 14 2
A fix_simple_utf8() 0 19 4
C strcspn() 0 52 12
B is_json() 0 29 8
A fixStrCaseHelper() 0 36 5
A int_to_hex() 0 7 2
B str_split_pattern() 0 49 11
D strstr() 0 92 18
A has_lowercase() 0 8 2
A json_encode() 0 10 2
A str_isubstr_first() 0 25 4
A is_base64() 0 20 5
A str_last_char() 0 16 4
A str_ireplace_beginning() 0 21 6
A hex_to_int() 0 14 3
A htmlentities() 0 28 3
A hex_to_chr() 0 3 1
A str_substr_before_first_separator() 0 32 6
F substr() 0 143 32
A isJson() 0 3 1
A wordwrap_per_line() 0 28 5
A strncmp() 0 19 4
A filter_input_array() 0 12 2
A str_insert() 0 28 4
A getSupportInfo() 0 13 3
A utf8_fix_win1252_chars() 0 3 1
A replace_diamond_question_mark() 0 38 5
D is_utf8_string() 0 134 28
A to_utf8_convert_helper() 0 28 5
B str_delimit() 0 33 8
B strtoupper() 0 54 10
A min() 0 14 3
A collapse_whitespace() 0 8 2
C html_entity_decode() 0 78 17
A str_starts_with_any() 0 17 5
B strrichr() 0 54 11
A split() 0 6 1
A str_istarts_with_any() 0 17 5
B str_contains_any() 0 29 8
A initEmojiData() 0 26 4
A remove_duplicates() 0 14 4
B str_slice() 0 33 10
F strpos() 0 131 27
A str_shuffle() 0 35 6
A strcmp() 0 9 2
B file_get_contents() 0 56 11
A str_word_count() 0 23 5
A strripos_in_byte() 0 12 4
A str_to_binary() 0 10 2
A symfony_polyfill_used() 0 16 5
B str_to_words() 0 36 8

How to fix   Complexity   

Complex Class

Complex classes like UTF8 often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UTF8, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace voku\helper;
6
7
final class UTF8
8
{
9
    /**
10
     * (CRLF|([ZWNJ-ZWJ]|T+|L*(LV?V+|LV|LVT)T*|L+|[^Control])[Extend]*|[Control])
11
     * This regular expression is a work around for http://bugs.exim.org/1279
12
     */
13
    const GRAPHEME_CLUSTER_RX = "(?:\r\n|(?:[ -~\x{200C}\x{200D}]|[ᆨ-ᇹ]+|[ᄀ-ᅟ]*(?:[가개갸걔거게겨계고과괘괴교구궈궤귀규그긔기까깨꺄꺠꺼께껴꼐꼬꽈꽤꾀꾜꾸꿔꿰뀌뀨끄끠끼나내냐냬너네녀녜노놔놰뇌뇨누눠눼뉘뉴느늬니다대댜댸더데뎌뎨도돠돼되됴두둬뒈뒤듀드듸디따때땨떄떠떼뗘뗴또똬뙈뙤뚀뚜뚸뛔뛰뜌뜨띄띠라래랴럐러레려례로롸뢔뢰료루뤄뤠뤼류르릐리마매먀먜머메며몌모뫄뫠뫼묘무뭐뭬뮈뮤므믜미바배뱌뱨버베벼볘보봐봬뵈뵤부붜붸뷔뷰브븨비빠빼뺘뺴뻐뻬뼈뼤뽀뽜뽸뾔뾰뿌뿨쀄쀠쀼쁘쁴삐사새샤섀서세셔셰소솨쇄쇠쇼수숴쉐쉬슈스싀시싸쌔쌰썌써쎄쎠쎼쏘쏴쐐쐬쑈쑤쒀쒜쒸쓔쓰씌씨아애야얘어에여예오와왜외요우워웨위유으의이자재쟈쟤저제져졔조좌좨죄죠주줘줴쥐쥬즈즤지짜째쨔쨰쩌쩨쪄쪠쪼쫘쫴쬐쬬쭈쭤쮀쮜쮸쯔쯰찌차채챠챼처체쳐쳬초촤쵀최쵸추춰췌취츄츠츼치카캐캬컈커케켜켸코콰쾌쾨쿄쿠쿼퀘퀴큐크킈키타태탸턔터테텨톄토톼퇘퇴툐투퉈퉤튀튜트틔티파패퍄퍠퍼페펴폐포퐈퐤푀표푸풔풰퓌퓨프픠피하해햐햬허헤혀혜호화홰회효후훠훼휘휴흐희히]?[ᅠ-ᆢ]+|[가-힣])[ᆨ-ᇹ]*|[ᄀ-ᅟ]+|[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}])[\p{Mn}\p{Me}\x{09BE}\x{09D7}\x{0B3E}\x{0B57}\x{0BBE}\x{0BD7}\x{0CC2}\x{0CD5}\x{0CD6}\x{0D3E}\x{0D57}\x{0DCF}\x{0DDF}\x{200C}\x{200D}\x{1D165}\x{1D16E}-\x{1D172}]*|[\p{Cc}\p{Cf}\p{Zl}\p{Zp}])";
14
15
    /**
16
     * Bom => Byte-Length
17
     *
18
     * INFO: https://en.wikipedia.org/wiki/Byte_order_mark
19
     *
20
     * @var array
21
     */
22
    private static $BOM = [
23
        "\xef\xbb\xbf"     => 3, // UTF-8 BOM
24
        ''              => 6, // UTF-8 BOM as "WINDOWS-1252" (one char has [maybe] more then one byte ...)
25
        "\x00\x00\xfe\xff" => 4, // UTF-32 (BE) BOM
26
        '  þÿ'             => 6, // UTF-32 (BE) BOM as "WINDOWS-1252"
27
        "\xff\xfe\x00\x00" => 4, // UTF-32 (LE) BOM
28
        'ÿþ  '             => 6, // UTF-32 (LE) BOM as "WINDOWS-1252"
29
        "\xfe\xff"         => 2, // UTF-16 (BE) BOM
30
        'þÿ'               => 4, // UTF-16 (BE) BOM as "WINDOWS-1252"
31
        "\xff\xfe"         => 2, // UTF-16 (LE) BOM
32
        'ÿþ'               => 4, // UTF-16 (LE) BOM as "WINDOWS-1252"
33
    ];
34
35
    /**
36
     * Numeric code point => UTF-8 Character
37
     *
38
     * url: http://www.w3schools.com/charsets/ref_utf_punctuation.asp
39
     *
40
     * @var array
41
     */
42
    private static $WHITESPACE = [
43
        // NUL Byte
44
        0 => "\x0",
45
        // Tab
46
        9 => "\x9",
47
        // New Line
48
        10 => "\xa",
49
        // Vertical Tab
50
        11 => "\xb",
51
        // Carriage Return
52
        13 => "\xd",
53
        // Ordinary Space
54
        32 => "\x20",
55
        // NO-BREAK SPACE
56
        160 => "\xc2\xa0",
57
        // OGHAM SPACE MARK
58
        5760 => "\xe1\x9a\x80",
59
        // MONGOLIAN VOWEL SEPARATOR
60
        6158 => "\xe1\xa0\x8e",
61
        // EN QUAD
62
        8192 => "\xe2\x80\x80",
63
        // EM QUAD
64
        8193 => "\xe2\x80\x81",
65
        // EN SPACE
66
        8194 => "\xe2\x80\x82",
67
        // EM SPACE
68
        8195 => "\xe2\x80\x83",
69
        // THREE-PER-EM SPACE
70
        8196 => "\xe2\x80\x84",
71
        // FOUR-PER-EM SPACE
72
        8197 => "\xe2\x80\x85",
73
        // SIX-PER-EM SPACE
74
        8198 => "\xe2\x80\x86",
75
        // FIGURE SPACE
76
        8199 => "\xe2\x80\x87",
77
        // PUNCTUATION SPACE
78
        8200 => "\xe2\x80\x88",
79
        // THIN SPACE
80
        8201 => "\xe2\x80\x89",
81
        //HAIR SPACE
82
        8202 => "\xe2\x80\x8a",
83
        // LINE SEPARATOR
84
        8232 => "\xe2\x80\xa8",
85
        // PARAGRAPH SEPARATOR
86
        8233 => "\xe2\x80\xa9",
87
        // NARROW NO-BREAK SPACE
88
        8239 => "\xe2\x80\xaf",
89
        // MEDIUM MATHEMATICAL SPACE
90
        8287 => "\xe2\x81\x9f",
91
        // IDEOGRAPHIC SPACE
92
        12288 => "\xe3\x80\x80",
93
    ];
94
95
    /**
96
     * @var array
97
     */
98
    private static $WHITESPACE_TABLE = [
99
        'SPACE'                     => "\x20",
100
        'NO-BREAK SPACE'            => "\xc2\xa0",
101
        'OGHAM SPACE MARK'          => "\xe1\x9a\x80",
102
        'EN QUAD'                   => "\xe2\x80\x80",
103
        'EM QUAD'                   => "\xe2\x80\x81",
104
        'EN SPACE'                  => "\xe2\x80\x82",
105
        'EM SPACE'                  => "\xe2\x80\x83",
106
        'THREE-PER-EM SPACE'        => "\xe2\x80\x84",
107
        'FOUR-PER-EM SPACE'         => "\xe2\x80\x85",
108
        'SIX-PER-EM SPACE'          => "\xe2\x80\x86",
109
        'FIGURE SPACE'              => "\xe2\x80\x87",
110
        'PUNCTUATION SPACE'         => "\xe2\x80\x88",
111
        'THIN SPACE'                => "\xe2\x80\x89",
112
        'HAIR SPACE'                => "\xe2\x80\x8a",
113
        'LINE SEPARATOR'            => "\xe2\x80\xa8",
114
        'PARAGRAPH SEPARATOR'       => "\xe2\x80\xa9",
115
        'ZERO WIDTH SPACE'          => "\xe2\x80\x8b",
116
        'NARROW NO-BREAK SPACE'     => "\xe2\x80\xaf",
117
        'MEDIUM MATHEMATICAL SPACE' => "\xe2\x81\x9f",
118
        'IDEOGRAPHIC SPACE'         => "\xe3\x80\x80",
119
        'HALFWIDTH HANGUL FILLER'   => "\xef\xbe\xa0",
120
    ];
121
122
    /**
123
     * @var array{upper: string[], lower: string[]}
0 ignored issues
show
Documentation Bug introduced by
The doc comment array{upper at position 0 could not be parsed: Unknown type name 'array{upper' at position 0 in array{upper.
Loading history...
124
     */
125
    private static $COMMON_CASE_FOLD = [
126
        'upper' => [
127
            'µ',
128
            'ſ',
129
            "\xCD\x85",
130
            'ς',
131
            'ẞ',
132
            "\xCF\x90",
133
            "\xCF\x91",
134
            "\xCF\x95",
135
            "\xCF\x96",
136
            "\xCF\xB0",
137
            "\xCF\xB1",
138
            "\xCF\xB5",
139
            "\xE1\xBA\x9B",
140
            "\xE1\xBE\xBE",
141
        ],
142
        'lower' => [
143
            'μ',
144
            's',
145
            'ι',
146
            'σ',
147
            'ß',
148
            'β',
149
            'θ',
150
            'φ',
151
            'π',
152
            'κ',
153
            'ρ',
154
            'ε',
155
            "\xE1\xB9\xA1",
156
            'ι',
157
        ],
158
    ];
159
160
    /**
161
     * @var array
162
     */
163
    private static $SUPPORT = [];
164
165
    /**
166
     * @var array|null
167
     */
168
    private static $BROKEN_UTF8_FIX;
169
170
    /**
171
     * @var array|null
172
     */
173
    private static $WIN1252_TO_UTF8;
174
175
    /**
176
     * @var array|null
177
     */
178
    private static $INTL_TRANSLITERATOR_LIST;
179
180
    /**
181
     * @var array|null
182
     */
183
    private static $ENCODINGS;
184
185
    /**
186
     * @var array|null
187
     */
188
    private static $ORD;
189
190
    /**
191
     * @var array|null
192
     */
193
    private static $EMOJI;
194
195
    /**
196
     * @var array|null
197
     */
198
    private static $EMOJI_VALUES_CACHE;
199
200
    /**
201
     * @var array|null
202
     */
203
    private static $EMOJI_KEYS_CACHE;
204
205
    /**
206
     * @var array|null
207
     */
208
    private static $EMOJI_KEYS_REVERSIBLE_CACHE;
209
210
    /**
211
     * @var array|null
212
     */
213
    private static $CHR;
214
215
    /**
216
     * __construct()
217
     */
218 33
    public function __construct()
219
    {
220 33
    }
221
222
    /**
223
     * Return the character at the specified position: $str[1] like functionality.
224
     *
225
     * @param string $str      <p>A UTF-8 string.</p>
226
     * @param int    $pos      <p>The position of character to return.</p>
227
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
228
     *
229
     * @return string single multi-byte character
230
     */
231 3
    public static function access(string $str, int $pos, string $encoding = 'UTF-8'): string
232
    {
233 3
        if ($str === '' || $pos < 0) {
234 2
            return '';
235
        }
236
237 3
        if ($encoding === 'UTF-8') {
238 3
            return (string) \mb_substr($str, $pos, 1);
239
        }
240
241
        return (string) self::substr($str, $pos, 1, $encoding);
242
    }
243
244
    /**
245
     * Prepends UTF-8 BOM character to the string and returns the whole string.
246
     *
247
     * INFO: If BOM already existed there, the Input string is returned.
248
     *
249
     * @param string $str <p>The input string.</p>
250
     *
251
     * @return string the output string that contains BOM
252
     */
253 2
    public static function add_bom_to_string(string $str): string
254
    {
255 2
        if (self::string_has_bom($str) === false) {
256 2
            $str = self::bom() . $str;
257
        }
258
259 2
        return $str;
260
    }
261
262
    /**
263
     * Changes all keys in an array.
264
     *
265
     * @param array  $array    <p>The array to work on</p>
266
     * @param int    $case     [optional] <p> Either <strong>CASE_UPPER</strong><br>
267
     *                         or <strong>CASE_LOWER</strong> (default)</p>
268
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
269
     *
270
     * @return string[]
271
     *                  <p>An array with its keys lower- or uppercased.</p>
272
     */
273 2
    public static function array_change_key_case(
274
        array $array,
275
        int $case = \CASE_LOWER,
276
        string $encoding = 'UTF-8'
277
    ): array {
278
        if (
279 2
            $case !== \CASE_LOWER
280
            &&
281 2
            $case !== \CASE_UPPER
282
        ) {
283
            $case = \CASE_LOWER;
284
        }
285
286 2
        $return = [];
287 2
        foreach ($array as $key => &$value) {
288 2
            $key = $case === \CASE_LOWER
289 2
                ? self::strtolower((string) $key, $encoding)
290 2
                : self::strtoupper((string) $key, $encoding);
291
292 2
            $return[$key] = $value;
293
        }
294
295 2
        return $return;
296
    }
297
298
    /**
299
     * Returns the substring between $start and $end, if found, or an empty
300
     * string. An optional offset may be supplied from which to begin the
301
     * search for the start string.
302
     *
303
     * @param string $str
304
     * @param string $start    <p>Delimiter marking the start of the substring.</p>
305
     * @param string $end      <p>Delimiter marking the end of the substring.</p>
306
     * @param int    $offset   [optional] <p>Index from which to begin the search. Default: 0</p>
307
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
308
     *
309
     * @return string
310
     */
311 16
    public static function between(
312
        string $str,
313
        string $start,
314
        string $end,
315
        int $offset = 0,
316
        string $encoding = 'UTF-8'
317
    ): string {
318 16
        if ($encoding === 'UTF-8') {
319 8
            $start_position = \mb_strpos($str, $start, $offset);
320 8
            if ($start_position === false) {
321 1
                return '';
322
            }
323
324 7
            $substr_index = $start_position + (int) \mb_strlen($start);
325 7
            $end_position = \mb_strpos($str, $end, $substr_index);
326
            if (
327 7
                $end_position === false
328
                ||
329 7
                $end_position === $substr_index
330
            ) {
331 2
                return '';
332
            }
333
334 5
            return (string) \mb_substr($str, $substr_index, $end_position - $substr_index);
335
        }
336
337 8
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
338
339 8
        $start_position = self::strpos($str, $start, $offset, $encoding);
340 8
        if ($start_position === false) {
341 1
            return '';
342
        }
343
344 7
        $substr_index = $start_position + (int) self::strlen($start, $encoding);
345 7
        $end_position = self::strpos($str, $end, $substr_index, $encoding);
346
        if (
347 7
            $end_position === false
348
            ||
349 7
            $end_position === $substr_index
350
        ) {
351 2
            return '';
352
        }
353
354 5
        return (string) self::substr(
355 5
            $str,
356 5
            $substr_index,
357 5
            $end_position - $substr_index,
358 5
            $encoding
359
        );
360
    }
361
362
    /**
363
     * Convert binary into a string.
364
     *
365
     * @param mixed $bin 1|0
366
     *
367
     * @return string
368
     */
369 2
    public static function binary_to_str($bin): string
370
    {
371 2
        if (!isset($bin[0])) {
372
            return '';
373
        }
374
375 2
        $convert = \base_convert($bin, 2, 16);
376 2
        if ($convert === '0') {
377 1
            return '';
378
        }
379
380 2
        return \pack('H*', $convert);
381
    }
382
383
    /**
384
     * Returns the UTF-8 Byte Order Mark Character.
385
     *
386
     * INFO: take a look at UTF8::$bom for e.g. UTF-16 and UTF-32 BOM values
387
     *
388
     * @return string UTF-8 Byte Order Mark
389
     */
390 4
    public static function bom(): string
391
    {
392 4
        return "\xef\xbb\xbf";
393
    }
394
395
    /**
396
     * @alias of UTF8::chr_map()
397
     *
398
     * @param callable $callback
399
     * @param string   $str
400
     *
401
     * @return string[]
402
     *
403
     * @see UTF8::chr_map()
404
     */
405 2
    public static function callback($callback, string $str): array
406
    {
407 2
        return self::chr_map($callback, $str);
408
    }
409
410
    /**
411
     * Returns the character at $index, with indexes starting at 0.
412
     *
413
     * @param string $str      <p>The input string.</p>
414
     * @param int    $index    <p>Position of the character.</p>
415
     * @param string $encoding [optional] <p>Default is UTF-8</p>
416
     *
417
     * @return string the character at $index
418
     */
419 9
    public static function char_at(string $str, int $index, string $encoding = 'UTF-8'): string
420
    {
421 9
        if ($encoding === 'UTF-8') {
422 5
            return (string) \mb_substr($str, $index, 1);
423
        }
424
425 4
        return (string) self::substr($str, $index, 1, $encoding);
426
    }
427
428
    /**
429
     * Returns an array consisting of the characters in the string.
430
     *
431
     * @param string $str <p>The input string.</p>
432
     *
433
     * @return string[] an array of chars
434
     */
435 3
    public static function chars(string $str): array
436
    {
437 3
        return self::str_split($str);
438
    }
439
440
    /**
441
     * This method will auto-detect your server environment for UTF-8 support.
442
     *
443
     * @return true|null
444
     *
445
     * @internal <p>You don't need to run it manually, it will be triggered if it's needed.</p>
446
     */
447 5
    public static function checkForSupport()
448
    {
449 5
        if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
450
            self::$SUPPORT['already_checked_via_portable_utf8'] = true;
451
452
            // http://php.net/manual/en/book.mbstring.php
453
            self::$SUPPORT['mbstring'] = self::mbstring_loaded();
454
            self::$SUPPORT['mbstring_func_overload'] = self::mbstring_overloaded();
455
            if (self::$SUPPORT['mbstring'] === true) {
456
                \mb_internal_encoding('UTF-8');
457
                /** @noinspection UnusedFunctionResultInspection */
458
                /** @noinspection PhpComposerExtensionStubsInspection */
459
                \mb_regex_encoding('UTF-8');
460
                self::$SUPPORT['mbstring_internal_encoding'] = 'UTF-8';
461
            }
462
463
            // http://php.net/manual/en/book.iconv.php
464
            self::$SUPPORT['iconv'] = self::iconv_loaded();
465
466
            // http://php.net/manual/en/book.intl.php
467
            self::$SUPPORT['intl'] = self::intl_loaded();
468
469
            // http://php.net/manual/en/class.intlchar.php
470
            self::$SUPPORT['intlChar'] = self::intlChar_loaded();
471
472
            // http://php.net/manual/en/book.ctype.php
473
            self::$SUPPORT['ctype'] = self::ctype_loaded();
474
475
            // http://php.net/manual/en/class.finfo.php
476
            self::$SUPPORT['finfo'] = self::finfo_loaded();
477
478
            // http://php.net/manual/en/book.json.php
479
            self::$SUPPORT['json'] = self::json_loaded();
480
481
            // http://php.net/manual/en/book.pcre.php
482
            self::$SUPPORT['pcre_utf8'] = self::pcre_utf8_support();
483
484
            self::$SUPPORT['symfony_polyfill_used'] = self::symfony_polyfill_used();
485
            if (self::$SUPPORT['symfony_polyfill_used'] === true) {
486
                \mb_internal_encoding('UTF-8');
487
                self::$SUPPORT['mbstring_internal_encoding'] = 'UTF-8';
488
            }
489
490
            return true;
491
        }
492
493 5
        return null;
494
    }
495
496
    /**
497
     * Generates a UTF-8 encoded character from the given code point.
498
     *
499
     * INFO: opposite to UTF8::ord()
500
     *
501
     * @param int|string $code_point <p>The code point for which to generate a character.</p>
502
     * @param string     $encoding   [optional] <p>Default is UTF-8</p>
503
     *
504
     * @return string|null multi-byte character, returns null on failure or empty input
505
     */
506 25
    public static function chr($code_point, string $encoding = 'UTF-8')
507
    {
508
        // init
509 25
        static $CHAR_CACHE = [];
510
511 25
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
512 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
513
        }
514
515
        if (
516 25
            $encoding !== 'UTF-8'
517
            &&
518 25
            $encoding !== 'ISO-8859-1'
519
            &&
520 25
            $encoding !== 'WINDOWS-1252'
521
            &&
522 25
            self::$SUPPORT['mbstring'] === false
523
        ) {
524
            \trigger_error('UTF8::chr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
525
        }
526
527 25
        $cache_key = $code_point . $encoding;
528 25
        if (isset($CHAR_CACHE[$cache_key]) === true) {
529 23
            return $CHAR_CACHE[$cache_key];
530
        }
531
532 14
        if ($code_point <= 127) { // use "simple"-char only until "\x80"
533
534 13
            if (self::$CHR === null) {
535
                self::$CHR = self::getData('chr');
536
            }
537
538
            /**
539
             * @psalm-suppress PossiblyNullArrayAccess
540
             */
541 13
            $chr = self::$CHR[$code_point];
542
543 13
            if ($encoding !== 'UTF-8') {
544 1
                $chr = self::encode($encoding, $chr);
545
            }
546
547 13
            return $CHAR_CACHE[$cache_key] = $chr;
548
        }
549
550
        //
551
        // fallback via "IntlChar"
552
        //
553
554 7
        if (self::$SUPPORT['intlChar'] === true) {
555
            /** @noinspection PhpComposerExtensionStubsInspection */
556 7
            $chr = \IntlChar::chr($code_point);
557
558 7
            if ($encoding !== 'UTF-8') {
559
                $chr = self::encode($encoding, $chr);
560
            }
561
562 7
            return $CHAR_CACHE[$cache_key] = $chr;
563
        }
564
565
        //
566
        // fallback via vanilla php
567
        //
568
569
        if (self::$CHR === null) {
570
            self::$CHR = self::getData('chr');
571
        }
572
573
        $code_point = (int) $code_point;
574
        if ($code_point <= 0x7F) {
575
            /**
576
             * @psalm-suppress PossiblyNullArrayAccess
577
             */
578
            $chr = self::$CHR[$code_point];
579
        } elseif ($code_point <= 0x7FF) {
580
            /**
581
             * @psalm-suppress PossiblyNullArrayAccess
582
             */
583
            $chr = self::$CHR[($code_point >> 6) + 0xC0] .
584
                   self::$CHR[($code_point & 0x3F) + 0x80];
585
        } elseif ($code_point <= 0xFFFF) {
586
            /**
587
             * @psalm-suppress PossiblyNullArrayAccess
588
             */
589
            $chr = self::$CHR[($code_point >> 12) + 0xE0] .
590
                   self::$CHR[(($code_point >> 6) & 0x3F) + 0x80] .
591
                   self::$CHR[($code_point & 0x3F) + 0x80];
592
        } else {
593
            /**
594
             * @psalm-suppress PossiblyNullArrayAccess
595
             */
596
            $chr = self::$CHR[($code_point >> 18) + 0xF0] .
597
                   self::$CHR[(($code_point >> 12) & 0x3F) + 0x80] .
598
                   self::$CHR[(($code_point >> 6) & 0x3F) + 0x80] .
599
                   self::$CHR[($code_point & 0x3F) + 0x80];
600
        }
601
602
        if ($encoding !== 'UTF-8') {
603
            $chr = self::encode($encoding, $chr);
604
        }
605
606
        return $CHAR_CACHE[$cache_key] = $chr;
607
    }
608
609
    /**
610
     * Applies callback to all characters of a string.
611
     *
612
     * @param callable $callback <p>The callback function.</p>
613
     * @param string   $str      <p>UTF-8 string to run callback on.</p>
614
     *
615
     * @return string[] the outcome of callback
616
     */
617 2
    public static function chr_map($callback, string $str): array
618
    {
619 2
        return \array_map(
620 2
            $callback,
621 2
            self::str_split($str)
622
        );
623
    }
624
625
    /**
626
     * Generates an array of byte length of each character of a Unicode string.
627
     *
628
     * 1 byte => U+0000  - U+007F
629
     * 2 byte => U+0080  - U+07FF
630
     * 3 byte => U+0800  - U+FFFF
631
     * 4 byte => U+10000 - U+10FFFF
632
     *
633
     * @param string $str <p>The original unicode string.</p>
634
     *
635
     * @return int[] an array of byte lengths of each character
636
     */
637 4
    public static function chr_size_list(string $str): array
638
    {
639 4
        if ($str === '') {
640 4
            return [];
641
        }
642
643 4
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
644
            return \array_map(
645
                static function (string $data): int {
646
                    // "mb_" is available if overload is used, so use it ...
647
                    return \mb_strlen($data, 'CP850'); // 8-BIT
648
                },
649
                self::str_split($str)
650
            );
651
        }
652
653 4
        return \array_map('\strlen', self::str_split($str));
654
    }
655
656
    /**
657
     * Get a decimal code representation of a specific character.
658
     *
659
     * @param string $char <p>The input character.</p>
660
     *
661
     * @return int
662
     */
663 4
    public static function chr_to_decimal(string $char): int
664
    {
665 4
        $code = self::ord($char[0]);
666 4
        $bytes = 1;
667
668 4
        if (!($code & 0x80)) {
669
            // 0xxxxxxx
670 4
            return $code;
671
        }
672
673 4
        if (($code & 0xe0) === 0xc0) {
674
            // 110xxxxx
675 4
            $bytes = 2;
676 4
            $code &= ~0xc0;
677 4
        } elseif (($code & 0xf0) === 0xe0) {
678
            // 1110xxxx
679 4
            $bytes = 3;
680 4
            $code &= ~0xe0;
681 2
        } elseif (($code & 0xf8) === 0xf0) {
682
            // 11110xxx
683 2
            $bytes = 4;
684 2
            $code &= ~0xf0;
685
        }
686
687 4
        for ($i = 2; $i <= $bytes; ++$i) {
688
            // 10xxxxxx
689 4
            $code = ($code << 6) + (self::ord($char[$i - 1]) & ~0x80);
690
        }
691
692 4
        return $code;
693
    }
694
695
    /**
696
     * Get hexadecimal code point (U+xxxx) of a UTF-8 encoded character.
697
     *
698
     * @param int|string $char   <p>The input character</p>
699
     * @param string     $prefix [optional]
700
     *
701
     * @return string The code point encoded as U+xxxx
702
     */
703 2
    public static function chr_to_hex($char, string $prefix = 'U+'): string
704
    {
705 2
        if ($char === '') {
706 2
            return '';
707
        }
708
709 2
        if ($char === '&#0;') {
710 2
            $char = '';
711
        }
712
713 2
        return self::int_to_hex(self::ord((string) $char), $prefix);
714
    }
715
716
    /**
717
     * alias for "UTF8::chr_to_decimal()"
718
     *
719
     * @param string $chr
720
     *
721
     * @return int
722
     *
723
     * @see UTF8::chr_to_decimal()
724
     * @deprecated <p>please use "UTF8::chr_to_decimal()"</p>
725
     */
726 2
    public static function chr_to_int(string $chr): int
727
    {
728 2
        return self::chr_to_decimal($chr);
729
    }
730
731
    /**
732
     * Splits a string into smaller chunks and multiple lines, using the specified line ending character.
733
     *
734
     * @param string $body         <p>The original string to be split.</p>
735
     * @param int    $chunk_length [optional] <p>The maximum character length of a chunk.</p>
736
     * @param string $end          [optional] <p>The character(s) to be inserted at the end of each chunk.</p>
737
     *
738
     * @return string the chunked string
739
     */
740 4
    public static function chunk_split(string $body, int $chunk_length = 76, string $end = "\r\n"): string
741
    {
742 4
        return \implode($end, self::str_split($body, $chunk_length));
743
    }
744
745
    /**
746
     * Accepts a string and removes all non-UTF-8 characters from it + extras if needed.
747
     *
748
     * @param string $str                           <p>The string to be sanitized.</p>
749
     * @param bool   $remove_bom                    [optional] <p>Set to true, if you need to remove UTF-BOM.</p>
750
     * @param bool   $normalize_whitespace          [optional] <p>Set to true, if you need to normalize the
751
     *                                              whitespace.</p>
752
     * @param bool   $normalize_msword              [optional] <p>Set to true, if you need to normalize MS Word chars
753
     *                                              e.g.: "…"
754
     *                                              => "..."</p>
755
     * @param bool   $keep_non_breaking_space       [optional] <p>Set to true, to keep non-breaking-spaces, in
756
     *                                              combination with
757
     *                                              $normalize_whitespace</p>
758
     * @param bool   $replace_diamond_question_mark [optional] <p>Set to true, if you need to remove diamond question
759
     *                                              mark e.g.: "�"</p>
760
     * @param bool   $remove_invisible_characters   [optional] <p>Set to false, if you not want to remove invisible
761
     *                                              characters e.g.: "\0"</p>
762
     *
763
     * @return string clean UTF-8 encoded string
764
     */
765 87
    public static function clean(
766
        string $str,
767
        bool $remove_bom = false,
768
        bool $normalize_whitespace = false,
769
        bool $normalize_msword = false,
770
        bool $keep_non_breaking_space = false,
771
        bool $replace_diamond_question_mark = false,
772
        bool $remove_invisible_characters = true
773
    ): string {
774
        // http://stackoverflow.com/questions/1401317/remove-non-utf8-characters-from-string
775
        // caused connection reset problem on larger strings
776
777 87
        $regex = '/
778
          (
779
            (?: [\x00-\x7F]               # single-byte sequences   0xxxxxxx
780
            |   [\xC0-\xDF][\x80-\xBF]    # double-byte sequences   110xxxxx 10xxxxxx
781
            |   [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences   1110xxxx 10xxxxxx * 2
782
            |   [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
783
            ){1,100}                      # ...one or more times
784
          )
785
        | ( [\x80-\xBF] )                 # invalid byte in range 10000000 - 10111111
786
        | ( [\xC0-\xFF] )                 # invalid byte in range 11000000 - 11111111
787
        /x';
788
        /** @noinspection NotOptimalRegularExpressionsInspection */
789 87
        $str = (string) \preg_replace($regex, '$1', $str);
790
791 87
        if ($replace_diamond_question_mark === true) {
792 33
            $str = self::replace_diamond_question_mark($str, '');
793
        }
794
795 87
        if ($remove_invisible_characters === true) {
796 87
            $str = self::remove_invisible_characters($str);
797
        }
798
799 87
        if ($normalize_whitespace === true) {
800 37
            $str = self::normalize_whitespace($str, $keep_non_breaking_space);
801
        }
802
803 87
        if ($normalize_msword === true) {
804 4
            $str = self::normalize_msword($str);
805
        }
806
807 87
        if ($remove_bom === true) {
808 37
            $str = self::remove_bom($str);
809
        }
810
811 87
        return $str;
812
    }
813
814
    /**
815
     * Clean-up a string and show only printable UTF-8 chars at the end  + fix UTF-8 encoding.
816
     *
817
     * @param string $str <p>The input string.</p>
818
     *
819
     * @return string
820
     */
821 33
    public static function cleanup($str): string
822
    {
823
        // init
824 33
        $str = (string) $str;
825
826 33
        if ($str === '') {
827 5
            return '';
828
        }
829
830
        // fixed ISO <-> UTF-8 Errors
831 33
        $str = self::fix_simple_utf8($str);
832
833
        // remove all none UTF-8 symbols
834
        // && remove diamond question mark (�)
835
        // && remove remove invisible characters (e.g. "\0")
836
        // && remove BOM
837
        // && normalize whitespace chars (but keep non-breaking-spaces)
838 33
        return self::clean(
839 33
            $str,
840 33
            true,
841 33
            true,
842 33
            false,
843 33
            true,
844 33
            true,
845 33
            true
846
        );
847
    }
848
849
    /**
850
     * Accepts a string or a array of strings and returns an array of Unicode code points.
851
     *
852
     * INFO: opposite to UTF8::string()
853
     *
854
     * @param string|string[] $arg     <p>A UTF-8 encoded string or an array of such strings.</p>
855
     * @param bool            $u_style <p>If True, will return code points in U+xxxx format,
856
     *                                 default, code points will be returned as integers.</p>
857
     *
858
     * @return array<int|string>
859
     *                           The array of code points:<br>
860
     *                           array<int> for $u_style === false<br>
861
     *                           array<string> for $u_style === true<br>
862
     */
863 12
    public static function codepoints($arg, bool $u_style = false): array
864
    {
865 12
        if (\is_string($arg) === true) {
866 12
            $arg = self::str_split($arg);
867
        }
868
869 12
        $arg = \array_map(
870
            [
871 12
                self::class,
872
                'ord',
873
            ],
874 12
            $arg
875
        );
876
877 12
        if (\count($arg) === 0) {
878 7
            return [];
879
        }
880
881 11
        if ($u_style === true) {
882 2
            $arg = \array_map(
883
                [
884 2
                    self::class,
885
                    'int_to_hex',
886
                ],
887 2
                $arg
888
            );
889
        }
890
891 11
        return $arg;
892
    }
893
894
    /**
895
     * Trims the string and replaces consecutive whitespace characters with a
896
     * single space. This includes tabs and newline characters, as well as
897
     * multibyte whitespace such as the thin space and ideographic space.
898
     *
899
     * @param string $str <p>The input string.</p>
900
     *
901
     * @return string string with a trimmed $str and condensed whitespace
902
     */
903 13
    public static function collapse_whitespace(string $str): string
904
    {
905 13
        if (self::$SUPPORT['mbstring'] === true) {
906
            /** @noinspection PhpComposerExtensionStubsInspection */
907 13
            return \trim((string) \mb_ereg_replace('[[:space:]]+', ' ', $str));
908
        }
909
910
        return \trim(self::regex_replace($str, '[[:space:]]+', ' '));
911
    }
912
913
    /**
914
     * Returns count of characters used in a string.
915
     *
916
     * @param string $str                     <p>The input string.</p>
917
     * @param bool   $clean_utf8              [optional] <p>Remove non UTF-8 chars from the string.</p>
918
     * @param bool   $try_to_use_mb_functions [optional] <p>Set to false, if you don't want to use
919
     *
920
     * @return int[] an associative array of Character as keys and
921
     *               their count as values
922
     */
923 19
    public static function count_chars(
924
        string $str,
925
        bool $clean_utf8 = false,
926
        bool $try_to_use_mb_functions = true
927
    ): array {
928 19
        return \array_count_values(
929 19
            self::str_split(
930 19
                $str,
931 19
                1,
932 19
                $clean_utf8,
933 19
                $try_to_use_mb_functions
934
            )
935
        );
936
    }
937
938
    /**
939
     * Remove css media-queries.
940
     *
941
     * @param string $str
942
     *
943
     * @return string
944
     */
945 1
    public static function css_stripe_media_queries(string $str): string
946
    {
947 1
        return (string) \preg_replace(
948 1
            '#@media\\s+(?:only\\s)?(?:[\\s{\\(]|screen|all)\\s?[^{]+{.*}\\s*}\\s*#isumU',
949 1
            '',
950 1
            $str
951
        );
952
    }
953
954
    /**
955
     * Checks whether ctype is available on the server.
956
     *
957
     * @return bool
958
     *              <strong>true</strong> if available, <strong>false</strong> otherwise
959
     */
960
    public static function ctype_loaded(): bool
961
    {
962
        return \extension_loaded('ctype');
963
    }
964
965
    /**
966
     * Converts an int value into a UTF-8 character.
967
     *
968
     * @param mixed $int
969
     *
970
     * @return string
971
     */
972 19
    public static function decimal_to_chr($int): string
973
    {
974 19
        return self::html_entity_decode('&#' . $int . ';', \ENT_QUOTES | \ENT_HTML5);
975
    }
976
977
    /**
978
     * Decodes a MIME header field
979
     *
980
     * @param string $str
981
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
982
     *
983
     * @return false|string
984
     *                      A decoded MIME field on success,
985
     *                      or false if an error occurs during the decoding
986
     */
987
    public static function decode_mimeheader($str, string $encoding = 'UTF-8')
988
    {
989
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
990
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
991
        }
992
993
        if (self::$SUPPORT['iconv'] === true) {
994
            return \iconv_mime_decode($str, \ICONV_MIME_DECODE_CONTINUE_ON_ERROR, $encoding);
995
        }
996
997
        if ($encoding !== 'UTF-8') {
998
            $str = self::encode($encoding, $str);
999
        }
1000
1001
        return \mb_decode_mimeheader($str);
1002
    }
1003
1004
    /**
1005
     * Decodes a string which was encoded by "UTF8::emoji_encode()".
1006
     *
1007
     * @param string $str                            <p>The input string.</p>
1008
     * @param bool   $use_reversible_string_mappings [optional] <p>
1009
     *                                               When <b>TRUE</b>, we se a reversible string mapping
1010
     *                                               between "emoji_encode" and "emoji_decode".</p>
1011
     *
1012
     * @return string
1013
     */
1014 9
    public static function emoji_decode(
1015
        string $str,
1016
        bool $use_reversible_string_mappings = false
1017
    ): string {
1018 9
        self::initEmojiData();
1019
1020 9
        if ($use_reversible_string_mappings === true) {
1021 9
            return (string) \str_replace(
1022 9
                (array) self::$EMOJI_KEYS_REVERSIBLE_CACHE,
1023 9
                (array) self::$EMOJI_VALUES_CACHE,
1024 9
                $str
1025
            );
1026
        }
1027
1028 1
        return (string) \str_replace(
1029 1
            (array) self::$EMOJI_KEYS_CACHE,
1030 1
            (array) self::$EMOJI_VALUES_CACHE,
1031 1
            $str
1032
        );
1033
    }
1034
1035
    /**
1036
     * Encode a string with emoji chars into a non-emoji string.
1037
     *
1038
     * @param string $str                            <p>The input string</p>
1039
     * @param bool   $use_reversible_string_mappings [optional] <p>
1040
     *                                               when <b>TRUE</b>, we se a reversible string mapping
1041
     *                                               between "emoji_encode" and "emoji_decode"</p>
1042
     *
1043
     * @return string
1044
     */
1045 12
    public static function emoji_encode(
1046
        string $str,
1047
        bool $use_reversible_string_mappings = false
1048
    ): string {
1049 12
        self::initEmojiData();
1050
1051 12
        if ($use_reversible_string_mappings === true) {
1052 9
            return (string) \str_replace(
1053 9
                (array) self::$EMOJI_VALUES_CACHE,
1054 9
                (array) self::$EMOJI_KEYS_REVERSIBLE_CACHE,
1055 9
                $str
1056
            );
1057
        }
1058
1059 4
        return (string) \str_replace(
1060 4
            (array) self::$EMOJI_VALUES_CACHE,
1061 4
            (array) self::$EMOJI_KEYS_CACHE,
1062 4
            $str
1063
        );
1064
    }
1065
1066
    /**
1067
     * Encode a string with a new charset-encoding.
1068
     *
1069
     * INFO:  This function will also try to fix broken / double encoding,
1070
     *        so you can call this function also on a UTF-8 string and you don't mess up the string.
1071
     *
1072
     * @param string $to_encoding                   <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.</p>
1073
     * @param string $str                           <p>The input string</p>
1074
     * @param bool   $auto_detect_the_from_encoding [optional] <p>Force the new encoding (we try to fix broken / double
1075
     *                                              encoding for UTF-8)<br> otherwise we auto-detect the current
1076
     *                                              string-encoding</p>
1077
     * @param string $from_encoding                 [optional] <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.<br>
1078
     *                                              A empty string will trigger the autodetect anyway.</p>
1079
     *
1080
     * @return string
1081
     *
1082
     * @psalm-suppress InvalidReturnStatement
1083
     */
1084 28
    public static function encode(
1085
        string $to_encoding,
1086
        string $str,
1087
        bool $auto_detect_the_from_encoding = true,
1088
        string $from_encoding = ''
1089
    ): string {
1090 28
        if ($str === '' || $to_encoding === '') {
1091 13
            return $str;
1092
        }
1093
1094 28
        if ($to_encoding !== 'UTF-8' && $to_encoding !== 'CP850') {
1095 7
            $to_encoding = self::normalize_encoding($to_encoding, 'UTF-8');
1096
        }
1097
1098 28
        if ($from_encoding && $from_encoding !== 'UTF-8' && $from_encoding !== 'CP850') {
1099 2
            $from_encoding = self::normalize_encoding($from_encoding, null);
1100
        }
1101
1102
        if (
1103 28
            $to_encoding
1104
            &&
1105 28
            $from_encoding
1106
            &&
1107 28
            $from_encoding === $to_encoding
1108
        ) {
1109
            return $str;
1110
        }
1111
1112 28
        if ($to_encoding === 'JSON') {
1113 1
            $return = self::json_encode($str);
1114 1
            if ($return === false) {
1115
                throw new \InvalidArgumentException('The input string [' . $str . '] can not be used for json_encode().');
1116
            }
1117
1118 1
            return $return;
1119
        }
1120 28
        if ($from_encoding === 'JSON') {
1121 1
            $str = self::json_decode($str);
1122 1
            $from_encoding = '';
1123
        }
1124
1125 28
        if ($to_encoding === 'BASE64') {
1126 2
            return \base64_encode($str);
1127
        }
1128 28
        if ($from_encoding === 'BASE64') {
1129 2
            $str = \base64_decode($str, true);
1130 2
            $from_encoding = '';
1131
        }
1132
1133 28
        if ($to_encoding === 'HTML-ENTITIES') {
1134 2
            return self::html_encode($str, true, 'UTF-8');
1135
        }
1136 28
        if ($from_encoding === 'HTML-ENTITIES') {
1137 2
            $str = self::html_entity_decode($str, \ENT_COMPAT, 'UTF-8');
1138 2
            $from_encoding = '';
1139
        }
1140
1141 28
        $from_encoding_auto_detected = false;
1142
        if (
1143 28
            $auto_detect_the_from_encoding === true
1144
            ||
1145 28
            !$from_encoding
1146
        ) {
1147 28
            $from_encoding_auto_detected = self::str_detect_encoding($str);
1148
        }
1149
1150
        // DEBUG
1151
        //var_dump($to_encoding, $from_encoding, $from_encoding_auto_detected, $str, "\n\n");
1152
1153 28
        if ($from_encoding_auto_detected !== false) {
1154
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
1155 24
            $from_encoding = $from_encoding_auto_detected;
1156 7
        } elseif ($auto_detect_the_from_encoding === true) {
1157
            // fallback for the "autodetect"-mode
1158 7
            return self::to_utf8($str);
1159
        }
1160
1161
        if (
1162 24
            !$from_encoding
1163
            ||
1164 24
            $from_encoding === $to_encoding
1165
        ) {
1166 15
            return $str;
1167
        }
1168
1169
        if (
1170 19
            $to_encoding === 'UTF-8'
1171
            &&
1172
            (
1173 17
                $from_encoding === 'WINDOWS-1252'
1174
                ||
1175 19
                $from_encoding === 'ISO-8859-1'
1176
            )
1177
        ) {
1178 13
            return self::to_utf8($str);
1179
        }
1180
1181
        if (
1182 12
            $to_encoding === 'ISO-8859-1'
1183
            &&
1184
            (
1185 6
                $from_encoding === 'WINDOWS-1252'
1186
                ||
1187 12
                $from_encoding === 'UTF-8'
1188
            )
1189
        ) {
1190 6
            return self::to_iso8859($str);
1191
        }
1192
1193
        if (
1194 10
            $to_encoding !== 'UTF-8'
1195
            &&
1196 10
            $to_encoding !== 'ISO-8859-1'
1197
            &&
1198 10
            $to_encoding !== 'WINDOWS-1252'
1199
            &&
1200 10
            self::$SUPPORT['mbstring'] === false
1201
        ) {
1202
            \trigger_error('UTF8::encode() without mbstring cannot handle "' . $to_encoding . '" encoding', \E_USER_WARNING);
1203
        }
1204
1205 10
        if (self::$SUPPORT['mbstring'] === true) {
1206
            // warning: do not use the symfony polyfill here
1207 10
            $str_encoded = \mb_convert_encoding(
1208 10
                $str,
1209 10
                $to_encoding,
1210 10
                $from_encoding
1211
            );
1212
1213 10
            if ($str_encoded) {
1214 10
                return $str_encoded;
1215
            }
1216
        }
1217
1218
        $return = \iconv($from_encoding, $to_encoding, $str);
1219
        if ($return !== false) {
1220
            return $return;
1221
        }
1222
1223
        return $str;
1224
    }
1225
1226
    /**
1227
     * @param string $str
1228
     * @param string $from_charset      [optional] <p>Set the input charset.</p>
1229
     * @param string $to_charset        [optional] <p>Set the output charset.</p>
1230
     * @param string $transfer_encoding [optional] <p>Set the transfer encoding.</p>
1231
     * @param string $linefeed          [optional] <p>Set the used linefeed.</p>
1232
     * @param int    $indent            [optional] <p>Set the max length indent.</p>
1233
     *
1234
     * @return false|string
1235
     *                      <p>An encoded MIME field on success,
1236
     *                      or false if an error occurs during the encoding.</p>
1237
     */
1238
    public static function encode_mimeheader(
1239
        $str,
1240
        $from_charset = 'UTF-8',
1241
        $to_charset = 'UTF-8',
1242
        $transfer_encoding = 'Q',
1243
        $linefeed = '\\r\\n',
1244
        $indent = 76
1245
    ) {
1246
        if ($from_charset !== 'UTF-8' && $from_charset !== 'CP850') {
1247
            $from_charset = self::normalize_encoding($from_charset, 'UTF-8');
1248
        }
1249
1250
        if ($to_charset !== 'UTF-8' && $to_charset !== 'CP850') {
1251
            $to_charset = self::normalize_encoding($to_charset, 'UTF-8');
1252
        }
1253
1254
        return \iconv_mime_encode(
1255
            '',
1256
            $str,
1257
            [
1258
                'scheme'           => $transfer_encoding,
1259
                'line-length'      => $indent,
1260
                'input-charset'    => $from_charset,
1261
                'output-charset'   => $to_charset,
1262
                'line-break-chars' => $linefeed,
1263
            ]
1264
        );
1265
    }
1266
1267
    /**
1268
     * Create an extract from a sentence, so if the search-string was found, it try to centered in the output.
1269
     *
1270
     * @param string   $str                       <p>The input string.</p>
1271
     * @param string   $search                    <p>The searched string.</p>
1272
     * @param int|null $length                    [optional] <p>Default: null === text->length / 2</p>
1273
     * @param string   $replacer_for_skipped_text [optional] <p>Default: …</p>
1274
     * @param string   $encoding                  [optional] <p>Set the charset for e.g. "mb_" function</p>
1275
     *
1276
     * @return string
1277
     */
1278 1
    public static function extract_text(
1279
        string $str,
1280
        string $search = '',
1281
        int $length = null,
1282
        string $replacer_for_skipped_text = '…',
1283
        string $encoding = 'UTF-8'
1284
    ): string {
1285 1
        if ($str === '') {
1286 1
            return '';
1287
        }
1288
1289 1
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
1290
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
1291
        }
1292
1293 1
        $trim_chars = "\t\r\n -_()!~?=+/*\\,.:;\"'[]{}`&";
1294
1295 1
        if ($length === null) {
1296 1
            $length = (int) \round((int) self::strlen($str, $encoding) / 2, 0);
1297
        }
1298
1299 1
        if ($search === '') {
1300 1
            if ($encoding === 'UTF-8') {
1301 1
                if ($length > 0) {
1302 1
                    $string_length = (int) \mb_strlen($str);
1303 1
                    $end = ($length - 1) > $string_length ? $string_length : ($length - 1);
1304
                } else {
1305 1
                    $end = 0;
1306
                }
1307
1308 1
                $pos = (int) \min(
1309 1
                    \mb_strpos($str, ' ', $end),
1310 1
                    \mb_strpos($str, '.', $end)
1311
                );
1312
            } else {
1313
                if ($length > 0) {
1314
                    $string_length = (int) self::strlen($str, $encoding);
1315
                    $end = ($length - 1) > $string_length ? $string_length : ($length - 1);
1316
                } else {
1317
                    $end = 0;
1318
                }
1319
1320
                $pos = (int) \min(
1321
                    self::strpos($str, ' ', $end, $encoding),
1322
                    self::strpos($str, '.', $end, $encoding)
1323
                );
1324
            }
1325
1326 1
            if ($pos) {
1327 1
                if ($encoding === 'UTF-8') {
1328 1
                    $str_sub = \mb_substr($str, 0, $pos);
1329
                } else {
1330
                    $str_sub = self::substr($str, 0, $pos, $encoding);
1331
                }
1332
1333 1
                if ($str_sub === false) {
1334
                    return '';
1335
                }
1336
1337 1
                return \rtrim($str_sub, $trim_chars) . $replacer_for_skipped_text;
1338
            }
1339
1340
            return $str;
1341
        }
1342
1343 1
        if ($encoding === 'UTF-8') {
1344 1
            $word_position = (int) \mb_stripos($str, $search);
1345 1
            $half_side = (int) ($word_position - $length / 2 + (int) \mb_strlen($search) / 2);
1346
        } else {
1347
            $word_position = (int) self::stripos($str, $search, 0, $encoding);
1348
            $half_side = (int) ($word_position - $length / 2 + (int) self::strlen($search, $encoding) / 2);
1349
        }
1350
1351 1
        $pos_start = 0;
1352 1
        if ($half_side > 0) {
1353 1
            if ($encoding === 'UTF-8') {
1354 1
                $half_text = \mb_substr($str, 0, $half_side);
1355
            } else {
1356
                $half_text = self::substr($str, 0, $half_side, $encoding);
1357
            }
1358 1
            if ($half_text !== false) {
1359 1
                if ($encoding === 'UTF-8') {
1360 1
                    $pos_start = (int) \max(
1361 1
                        \mb_strrpos($half_text, ' '),
1362 1
                        \mb_strrpos($half_text, '.')
1363
                    );
1364
                } else {
1365
                    $pos_start = (int) \max(
1366
                        self::strrpos($half_text, ' ', 0, $encoding),
1367
                        self::strrpos($half_text, '.', 0, $encoding)
1368
                    );
1369
                }
1370
            }
1371
        }
1372
1373 1
        if ($word_position && $half_side > 0) {
1374 1
            $offset = $pos_start + $length - 1;
1375 1
            $real_length = (int) self::strlen($str, $encoding);
1376
1377 1
            if ($offset > $real_length) {
1378
                $offset = $real_length;
1379
            }
1380
1381 1
            if ($encoding === 'UTF-8') {
1382 1
                $pos_end = (int) \min(
1383 1
                    \mb_strpos($str, ' ', $offset),
1384 1
                    \mb_strpos($str, '.', $offset)
1385 1
                ) - $pos_start;
1386
            } else {
1387
                $pos_end = (int) \min(
1388
                    self::strpos($str, ' ', $offset, $encoding),
1389
                    self::strpos($str, '.', $offset, $encoding)
1390
                ) - $pos_start;
1391
            }
1392
1393 1
            if (!$pos_end || $pos_end <= 0) {
1394 1
                if ($encoding === 'UTF-8') {
1395 1
                    $str_sub = \mb_substr($str, $pos_start, (int) \mb_strlen($str));
1396
                } else {
1397
                    $str_sub = self::substr($str, $pos_start, (int) self::strlen($str, $encoding), $encoding);
1398
                }
1399 1
                if ($str_sub !== false) {
1400 1
                    $extract = $replacer_for_skipped_text . \ltrim($str_sub, $trim_chars);
1401
                } else {
1402 1
                    $extract = '';
1403
                }
1404
            } else {
1405 1
                if ($encoding === 'UTF-8') {
1406 1
                    $str_sub = \mb_substr($str, $pos_start, $pos_end);
1407
                } else {
1408
                    $str_sub = self::substr($str, $pos_start, $pos_end, $encoding);
1409
                }
1410 1
                if ($str_sub !== false) {
1411 1
                    $extract = $replacer_for_skipped_text . \trim($str_sub, $trim_chars) . $replacer_for_skipped_text;
1412
                } else {
1413 1
                    $extract = '';
1414
                }
1415
            }
1416
        } else {
1417 1
            $offset = $length - 1;
1418 1
            $true_length = (int) self::strlen($str, $encoding);
1419
1420 1
            if ($offset > $true_length) {
1421
                $offset = $true_length;
1422
            }
1423
1424 1
            if ($encoding === 'UTF-8') {
1425 1
                $pos_end = (int) \min(
1426 1
                    \mb_strpos($str, ' ', $offset),
1427 1
                    \mb_strpos($str, '.', $offset)
1428
                );
1429
            } else {
1430
                $pos_end = (int) \min(
1431
                    self::strpos($str, ' ', $offset, $encoding),
1432
                    self::strpos($str, '.', $offset, $encoding)
1433
                );
1434
            }
1435
1436 1
            if ($pos_end) {
1437 1
                if ($encoding === 'UTF-8') {
1438 1
                    $str_sub = \mb_substr($str, 0, $pos_end);
1439
                } else {
1440
                    $str_sub = self::substr($str, 0, $pos_end, $encoding);
1441
                }
1442 1
                if ($str_sub !== false) {
1443 1
                    $extract = \rtrim($str_sub, $trim_chars) . $replacer_for_skipped_text;
1444
                } else {
1445 1
                    $extract = '';
1446
                }
1447
            } else {
1448 1
                $extract = $str;
1449
            }
1450
        }
1451
1452 1
        return $extract;
1453
    }
1454
1455
    /**
1456
     * Reads entire file into a string.
1457
     *
1458
     * WARNING: Do not use UTF-8 Option ($convert_to_utf8) for binary files (e.g.: images) !!!
1459
     *
1460
     * @see http://php.net/manual/en/function.file-get-contents.php
1461
     *
1462
     * @param string        $filename         <p>
1463
     *                                        Name of the file to read.
1464
     *                                        </p>
1465
     * @param bool          $use_include_path [optional] <p>
1466
     *                                        Prior to PHP 5, this parameter is called
1467
     *                                        use_include_path and is a bool.
1468
     *                                        As of PHP 5 the FILE_USE_INCLUDE_PATH can be used
1469
     *                                        to trigger include path
1470
     *                                        search.
1471
     *                                        </p>
1472
     * @param resource|null $context          [optional] <p>
1473
     *                                        A valid context resource created with
1474
     *                                        stream_context_create. If you don't need to use a
1475
     *                                        custom context, you can skip this parameter by &null;.
1476
     *                                        </p>
1477
     * @param int|null      $offset           [optional] <p>
1478
     *                                        The offset where the reading starts.
1479
     *                                        </p>
1480
     * @param int|null      $max_length       [optional] <p>
1481
     *                                        Maximum length of data read. The default is to read until end
1482
     *                                        of file is reached.
1483
     *                                        </p>
1484
     * @param int           $timeout          <p>The time in seconds for the timeout.</p>
1485
     * @param bool          $convert_to_utf8  <strong>WARNING!!!</strong> <p>Maybe you can't use this option for
1486
     *                                        some files, because they used non default utf-8 chars. Binary files
1487
     *                                        like images or pdf will not be converted.</p>
1488
     * @param string        $from_encoding    [optional] <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.<br>
1489
     *                                        A empty string will trigger the autodetect anyway.</p>
1490
     *
1491
     * @return false|string
1492
     *                      <p>The function returns the read data as string or <b>false</b> on failure.</p>
1493
     */
1494 12
    public static function file_get_contents(
1495
        string $filename,
1496
        bool $use_include_path = false,
1497
        $context = null,
1498
        int $offset = null,
1499
        int $max_length = null,
1500
        int $timeout = 10,
1501
        bool $convert_to_utf8 = true,
1502
        string $from_encoding = ''
1503
    ) {
1504
        // init
1505 12
        $filename = \filter_var($filename, \FILTER_SANITIZE_STRING);
1506
        /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
1507 12
        if ($filename === false) {
1508
            return false;
1509
        }
1510
1511 12
        if ($timeout && $context === null) {
1512 9
            $context = \stream_context_create(
1513
                [
1514
                    'http' => [
1515 9
                        'timeout' => $timeout,
1516
                    ],
1517
                ]
1518
            );
1519
        }
1520
1521 12
        if ($offset === null) {
1522 12
            $offset = 0;
1523
        }
1524
1525 12
        if (\is_int($max_length) === true) {
1526 2
            $data = \file_get_contents($filename, $use_include_path, $context, $offset, $max_length);
1527
        } else {
1528 12
            $data = \file_get_contents($filename, $use_include_path, $context, $offset);
1529
        }
1530
1531
        // return false on error
1532 12
        if ($data === false) {
1533
            return false;
1534
        }
1535
1536 12
        if ($convert_to_utf8 === true) {
1537
            if (
1538 12
                self::is_binary($data, true) !== true
1539
                ||
1540 9
                self::is_utf16($data, false) !== false
1541
                ||
1542 12
                self::is_utf32($data, false) !== false
1543
            ) {
1544 9
                $data = self::encode('UTF-8', $data, false, $from_encoding);
1545 9
                $data = self::cleanup($data);
1546
            }
1547
        }
1548
1549 12
        return $data;
1550
    }
1551
1552
    /**
1553
     * Checks if a file starts with BOM (Byte Order Mark) character.
1554
     *
1555
     * @param string $file_path <p>Path to a valid file.</p>
1556
     *
1557
     * @throws \RuntimeException if file_get_contents() returned false
1558
     *
1559
     * @return bool
1560
     *              <p><strong>true</strong> if the file has BOM at the start, <strong>false</strong> otherwise</p>
1561
     */
1562 2
    public static function file_has_bom(string $file_path): bool
1563
    {
1564 2
        $file_content = \file_get_contents($file_path);
1565 2
        if ($file_content === false) {
1566
            throw new \RuntimeException('file_get_contents() returned false for:' . $file_path);
1567
        }
1568
1569 2
        return self::string_has_bom($file_content);
1570
    }
1571
1572
    /**
1573
     * Normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1574
     *
1575
     * @param mixed  $var
1576
     * @param int    $normalization_form
1577
     * @param string $leading_combining
1578
     *
1579
     * @return mixed
1580
     */
1581 62
    public static function filter(
1582
        $var,
1583
        int $normalization_form = \Normalizer::NFC,
1584
        string $leading_combining = '◌'
1585
    ) {
1586 62
        switch (\gettype($var)) {
1587 62
            case 'array':
1588
                /** @noinspection ForeachSourceInspection */
1589 6
                foreach ($var as $k => &$v) {
1590 6
                    $v = self::filter($v, $normalization_form, $leading_combining);
1591
                }
1592 6
                unset($v);
1593
1594 6
                break;
1595 62
            case 'object':
1596
                /** @noinspection ForeachSourceInspection */
1597 4
                foreach ($var as $k => &$v) {
1598 4
                    $v = self::filter($v, $normalization_form, $leading_combining);
1599
                }
1600 4
                unset($v);
1601
1602 4
                break;
1603 62
            case 'string':
1604
1605 62
                if (\strpos($var, "\r") !== false) {
1606
                    // Workaround https://bugs.php.net/65732
1607 3
                    $var = self::normalize_line_ending($var);
1608
                }
1609
1610 62
                if (ASCII::is_ascii($var) === false) {
1611 32
                    if (\Normalizer::isNormalized($var, $normalization_form)) {
1612 27
                        $n = '-';
1613
                    } else {
1614 12
                        $n = \Normalizer::normalize($var, $normalization_form);
1615
1616 12
                        if (isset($n[0])) {
1617 7
                            $var = $n;
1618
                        } else {
1619 8
                            $var = self::encode('UTF-8', $var, true);
1620
                        }
1621
                    }
1622
1623
                    if (
1624 32
                        $var[0] >= "\x80"
1625
                        &&
1626 32
                        isset($n[0], $leading_combining[0])
1627
                        &&
1628 32
                        \preg_match('/^\\p{Mn}/u', $var)
1629
                    ) {
1630
                        // Prevent leading combining chars
1631
                        // for NFC-safe concatenations.
1632 3
                        $var = $leading_combining . $var;
1633
                    }
1634
                }
1635
1636 62
                break;
1637
        }
1638
1639 62
        return $var;
1640
    }
1641
1642
    /**
1643
     * "filter_input()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1644
     *
1645
     * Gets a specific external variable by name and optionally filters it
1646
     *
1647
     * @see http://php.net/manual/en/function.filter-input.php
1648
     *
1649
     * @param int    $type          <p>
1650
     *                              One of <b>INPUT_GET</b>, <b>INPUT_POST</b>,
1651
     *                              <b>INPUT_COOKIE</b>, <b>INPUT_SERVER</b>, or
1652
     *                              <b>INPUT_ENV</b>.
1653
     *                              </p>
1654
     * @param string $variable_name <p>
1655
     *                              Name of a variable to get.
1656
     *                              </p>
1657
     * @param int    $filter        [optional] <p>
1658
     *                              The ID of the filter to apply. The
1659
     *                              manual page lists the available filters.
1660
     *                              </p>
1661
     * @param mixed  $options       [optional] <p>
1662
     *                              Associative array of options or bitwise disjunction of flags. If filter
1663
     *                              accepts options, flags can be provided in "flags" field of array.
1664
     *                              </p>
1665
     *
1666
     * @return mixed Value of the requested variable on success, <b>FALSE</b> if the filter fails, or <b>NULL</b> if the
1667
     *               <i>variable_name</i> variable is not set. If the flag <b>FILTER_NULL_ON_FAILURE</b> is used, it
1668
     *               returns <b>FALSE</b> if the variable is not set and <b>NULL</b> if the filter fails.
1669
     */
1670
    public static function filter_input(
1671
        int $type,
1672
        string $variable_name,
1673
        int $filter = \FILTER_DEFAULT,
1674
        $options = null
1675
    ) {
1676
        if (\func_num_args() < 4) {
1677
            $var = \filter_input($type, $variable_name, $filter);
1678
        } else {
1679
            $var = \filter_input($type, $variable_name, $filter, $options);
1680
        }
1681
1682
        return self::filter($var);
1683
    }
1684
1685
    /**
1686
     * "filter_input_array()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1687
     *
1688
     * Gets external variables and optionally filters them
1689
     *
1690
     * @see http://php.net/manual/en/function.filter-input-array.php
1691
     *
1692
     * @param int   $type       <p>
1693
     *                          One of <b>INPUT_GET</b>, <b>INPUT_POST</b>,
1694
     *                          <b>INPUT_COOKIE</b>, <b>INPUT_SERVER</b>, or
1695
     *                          <b>INPUT_ENV</b>.
1696
     *                          </p>
1697
     * @param mixed $definition [optional] <p>
1698
     *                          An array defining the arguments. A valid key is a string
1699
     *                          containing a variable name and a valid value is either a filter type, or an array
1700
     *                          optionally specifying the filter, flags and options. If the value is an
1701
     *                          array, valid keys are filter which specifies the
1702
     *                          filter type,
1703
     *                          flags which specifies any flags that apply to the
1704
     *                          filter, and options which specifies any options that
1705
     *                          apply to the filter. See the example below for a better understanding.
1706
     *                          </p>
1707
     *                          <p>
1708
     *                          This parameter can be also an integer holding a filter constant. Then all values in the
1709
     *                          input array are filtered by this filter.
1710
     *                          </p>
1711
     * @param bool  $add_empty  [optional] <p>
1712
     *                          Add missing keys as <b>NULL</b> to the return value.
1713
     *                          </p>
1714
     *
1715
     * @return mixed An array containing the values of the requested variables on success, or <b>FALSE</b> on failure.
1716
     *               An array value will be <b>FALSE</b> if the filter fails, or <b>NULL</b> if the variable is not
1717
     *               set. Or if the flag <b>FILTER_NULL_ON_FAILURE</b> is used, it returns <b>FALSE</b> if the variable
1718
     *               is not set and <b>NULL</b> if the filter fails.
1719
     */
1720
    public static function filter_input_array(
1721
        int $type,
1722
        $definition = null,
1723
        bool $add_empty = true
1724
    ) {
1725
        if (\func_num_args() < 2) {
1726
            $a = \filter_input_array($type);
1727
        } else {
1728
            $a = \filter_input_array($type, $definition, $add_empty);
1729
        }
1730
1731
        return self::filter($a);
1732
    }
1733
1734
    /**
1735
     * "filter_var()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1736
     *
1737
     * Filters a variable with a specified filter
1738
     *
1739
     * @see http://php.net/manual/en/function.filter-var.php
1740
     *
1741
     * @param mixed $variable <p>
1742
     *                        Value to filter.
1743
     *                        </p>
1744
     * @param int   $filter   [optional] <p>
1745
     *                        The ID of the filter to apply. The
1746
     *                        manual page lists the available filters.
1747
     *                        </p>
1748
     * @param mixed $options  [optional] <p>
1749
     *                        Associative array of options or bitwise disjunction of flags. If filter
1750
     *                        accepts options, flags can be provided in "flags" field of array. For
1751
     *                        the "callback" filter, callable type should be passed. The
1752
     *                        callback must accept one argument, the value to be filtered, and return
1753
     *                        the value after filtering/sanitizing it.
1754
     *                        </p>
1755
     *                        <p>
1756
     *                        <code>
1757
     *                        // for filters that accept options, use this format
1758
     *                        $options = array(
1759
     *                        'options' => array(
1760
     *                        'default' => 3, // value to return if the filter fails
1761
     *                        // other options here
1762
     *                        'min_range' => 0
1763
     *                        ),
1764
     *                        'flags' => FILTER_FLAG_ALLOW_OCTAL,
1765
     *                        );
1766
     *                        $var = filter_var('0755', FILTER_VALIDATE_INT, $options);
1767
     *                        // for filter that only accept flags, you can pass them directly
1768
     *                        $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
1769
     *                        // for filter that only accept flags, you can also pass as an array
1770
     *                        $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
1771
     *                        array('flags' => FILTER_NULL_ON_FAILURE));
1772
     *                        // callback validate filter
1773
     *                        function foo($value)
1774
     *                        {
1775
     *                        // Expected format: Surname, GivenNames
1776
     *                        if (strpos($value, ", ") === false) return false;
1777
     *                        list($surname, $givennames) = explode(", ", $value, 2);
1778
     *                        $empty = (empty($surname) || empty($givennames));
1779
     *                        $notstrings = (!is_string($surname) || !is_string($givennames));
1780
     *                        if ($empty || $notstrings) {
1781
     *                        return false;
1782
     *                        } else {
1783
     *                        return $value;
1784
     *                        }
1785
     *                        }
1786
     *                        $var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));
1787
     *                        </code>
1788
     *                        </p>
1789
     *
1790
     * @return mixed the filtered data, or <b>FALSE</b> if the filter fails
1791
     */
1792 2
    public static function filter_var(
1793
        $variable,
1794
        int $filter = \FILTER_DEFAULT,
1795
        $options = null
1796
    ) {
1797 2
        if (\func_num_args() < 3) {
1798 2
            $variable = \filter_var($variable, $filter);
1799
        } else {
1800 2
            $variable = \filter_var($variable, $filter, $options);
1801
        }
1802
1803 2
        return self::filter($variable);
1804
    }
1805
1806
    /**
1807
     * "filter_var_array()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1808
     *
1809
     * Gets multiple variables and optionally filters them
1810
     *
1811
     * @see http://php.net/manual/en/function.filter-var-array.php
1812
     *
1813
     * @param array $data       <p>
1814
     *                          An array with string keys containing the data to filter.
1815
     *                          </p>
1816
     * @param mixed $definition [optional] <p>
1817
     *                          An array defining the arguments. A valid key is a string
1818
     *                          containing a variable name and a valid value is either a
1819
     *                          filter type, or an
1820
     *                          array optionally specifying the filter, flags and options.
1821
     *                          If the value is an array, valid keys are filter
1822
     *                          which specifies the filter type,
1823
     *                          flags which specifies any flags that apply to the
1824
     *                          filter, and options which specifies any options that
1825
     *                          apply to the filter. See the example below for a better understanding.
1826
     *                          </p>
1827
     *                          <p>
1828
     *                          This parameter can be also an integer holding a filter constant. Then all values in the
1829
     *                          input array are filtered by this filter.
1830
     *                          </p>
1831
     * @param bool  $add_empty  [optional] <p>
1832
     *                          Add missing keys as <b>NULL</b> to the return value.
1833
     *                          </p>
1834
     *
1835
     * @return mixed an array containing the values of the requested variables on success, or <b>FALSE</b> on failure.
1836
     *               An array value will be <b>FALSE</b> if the filter fails, or <b>NULL</b> if the variable is not
1837
     *               set
1838
     */
1839 2
    public static function filter_var_array(
1840
        array $data,
1841
        $definition = null,
1842
        bool $add_empty = true
1843
    ) {
1844 2
        if (\func_num_args() < 2) {
1845 2
            $a = \filter_var_array($data);
1846
        } else {
1847 2
            $a = \filter_var_array($data, $definition, $add_empty);
1848
        }
1849
1850 2
        return self::filter($a);
1851
    }
1852
1853
    /**
1854
     * Checks whether finfo is available on the server.
1855
     *
1856
     * @return bool
1857
     *              <strong>true</strong> if available, <strong>false</strong> otherwise
1858
     */
1859
    public static function finfo_loaded(): bool
1860
    {
1861
        return \class_exists('finfo');
1862
    }
1863
1864
    /**
1865
     * Returns the first $n characters of the string.
1866
     *
1867
     * @param string $str      <p>The input string.</p>
1868
     * @param int    $n        <p>Number of characters to retrieve from the start.</p>
1869
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
1870
     *
1871
     * @return string
1872
     */
1873 13
    public static function first_char(
1874
        string $str,
1875
        int $n = 1,
1876
        string $encoding = 'UTF-8'
1877
    ): string {
1878 13
        if ($str === '' || $n <= 0) {
1879 5
            return '';
1880
        }
1881
1882 8
        if ($encoding === 'UTF-8') {
1883 4
            return (string) \mb_substr($str, 0, $n);
1884
        }
1885
1886 4
        return (string) self::substr($str, 0, $n, $encoding);
1887
    }
1888
1889
    /**
1890
     * Check if the number of Unicode characters isn't greater than the specified integer.
1891
     *
1892
     * @param string $str      the original string to be checked
1893
     * @param int    $box_size the size in number of chars to be checked against string
1894
     *
1895
     * @return bool true if string is less than or equal to $box_size, false otherwise
1896
     */
1897 2
    public static function fits_inside(string $str, int $box_size): bool
1898
    {
1899 2
        return (int) self::strlen($str) <= $box_size;
1900
    }
1901
1902
    /**
1903
     * Try to fix simple broken UTF-8 strings.
1904
     *
1905
     * INFO: Take a look at "UTF8::fix_utf8()" if you need a more advanced fix for broken UTF-8 strings.
1906
     *
1907
     * If you received an UTF-8 string that was converted from Windows-1252 as it was ISO-8859-1
1908
     * (ignoring Windows-1252 chars from 80 to 9F) use this function to fix it.
1909
     * See: http://en.wikipedia.org/wiki/Windows-1252
1910
     *
1911
     * @param string $str <p>The input string</p>
1912
     *
1913
     * @return string
1914
     */
1915 46
    public static function fix_simple_utf8(string $str): string
1916
    {
1917 46
        if ($str === '') {
1918 4
            return '';
1919
        }
1920
1921 46
        static $BROKEN_UTF8_TO_UTF8_KEYS_CACHE = null;
1922 46
        static $BROKEN_UTF8_TO_UTF8_VALUES_CACHE = null;
1923
1924 46
        if ($BROKEN_UTF8_TO_UTF8_KEYS_CACHE === null) {
1925 1
            if (self::$BROKEN_UTF8_FIX === null) {
1926 1
                self::$BROKEN_UTF8_FIX = self::getData('utf8_fix');
1927
            }
1928
1929 1
            $BROKEN_UTF8_TO_UTF8_KEYS_CACHE = \array_keys(self::$BROKEN_UTF8_FIX);
1930 1
            $BROKEN_UTF8_TO_UTF8_VALUES_CACHE = \array_values(self::$BROKEN_UTF8_FIX);
1931
        }
1932
1933 46
        return \str_replace($BROKEN_UTF8_TO_UTF8_KEYS_CACHE, $BROKEN_UTF8_TO_UTF8_VALUES_CACHE, $str);
1934
    }
1935
1936
    /**
1937
     * Fix a double (or multiple) encoded UTF8 string.
1938
     *
1939
     * @param string|string[] $str you can use a string or an array of strings
1940
     *
1941
     * @return string|string[]
1942
     *                         Will return the fixed input-"array" or
1943
     *                         the fixed input-"string"
1944
     *
1945
     * @psalm-suppress InvalidReturnType
1946
     */
1947 2
    public static function fix_utf8($str)
1948
    {
1949 2
        if (\is_array($str) === true) {
1950 2
            foreach ($str as $k => &$v) {
1951 2
                $v = self::fix_utf8($v);
1952
            }
1953 2
            unset($v);
1954
1955
            /**
1956
             * @psalm-suppress InvalidReturnStatement
1957
             */
1958 2
            return $str;
1959
        }
1960
1961 2
        $str = (string) $str;
1962 2
        $last = '';
1963 2
        while ($last !== $str) {
1964 2
            $last = $str;
1965
            /**
1966
             * @psalm-suppress PossiblyInvalidArgument
1967
             */
1968 2
            $str = self::to_utf8(
1969 2
                self::utf8_decode($str, true)
1970
            );
1971
        }
1972
1973
        /**
1974
         * @psalm-suppress InvalidReturnStatement
1975
         */
1976 2
        return $str;
1977
    }
1978
1979
    /**
1980
     * Get character of a specific character.
1981
     *
1982
     * @param string $char
1983
     *
1984
     * @return string 'RTL' or 'LTR'
1985
     */
1986 2
    public static function getCharDirection(string $char): string
1987
    {
1988 2
        if (self::$SUPPORT['intlChar'] === true) {
1989
            /** @noinspection PhpComposerExtensionStubsInspection */
1990 2
            $tmp_return = \IntlChar::charDirection($char);
1991
1992
            // from "IntlChar"-Class
1993
            $char_direction = [
1994 2
                'RTL' => [1, 13, 14, 15, 21],
1995
                'LTR' => [0, 11, 12, 20],
1996
            ];
1997
1998 2
            if (\in_array($tmp_return, $char_direction['LTR'], true)) {
1999
                return 'LTR';
2000
            }
2001
2002 2
            if (\in_array($tmp_return, $char_direction['RTL'], true)) {
2003 2
                return 'RTL';
2004
            }
2005
        }
2006
2007 2
        $c = static::chr_to_decimal($char);
2008
2009 2
        if (!($c >= 0x5be && $c <= 0x10b7f)) {
2010 2
            return 'LTR';
2011
        }
2012
2013 2
        if ($c <= 0x85e) {
2014 2
            if ($c === 0x5be ||
2015 2
                $c === 0x5c0 ||
2016 2
                $c === 0x5c3 ||
2017 2
                $c === 0x5c6 ||
2018 2
                ($c >= 0x5d0 && $c <= 0x5ea) ||
2019 2
                ($c >= 0x5f0 && $c <= 0x5f4) ||
2020 2
                $c === 0x608 ||
2021 2
                $c === 0x60b ||
2022 2
                $c === 0x60d ||
2023 2
                $c === 0x61b ||
2024 2
                ($c >= 0x61e && $c <= 0x64a) ||
2025
                ($c >= 0x66d && $c <= 0x66f) ||
2026
                ($c >= 0x671 && $c <= 0x6d5) ||
2027
                ($c >= 0x6e5 && $c <= 0x6e6) ||
2028
                ($c >= 0x6ee && $c <= 0x6ef) ||
2029
                ($c >= 0x6fa && $c <= 0x70d) ||
2030
                $c === 0x710 ||
2031
                ($c >= 0x712 && $c <= 0x72f) ||
2032
                ($c >= 0x74d && $c <= 0x7a5) ||
2033
                $c === 0x7b1 ||
2034
                ($c >= 0x7c0 && $c <= 0x7ea) ||
2035
                ($c >= 0x7f4 && $c <= 0x7f5) ||
2036
                $c === 0x7fa ||
2037
                ($c >= 0x800 && $c <= 0x815) ||
2038
                $c === 0x81a ||
2039
                $c === 0x824 ||
2040
                $c === 0x828 ||
2041
                ($c >= 0x830 && $c <= 0x83e) ||
2042
                ($c >= 0x840 && $c <= 0x858) ||
2043 2
                $c === 0x85e
2044
            ) {
2045 2
                return 'RTL';
2046
            }
2047 2
        } elseif ($c === 0x200f) {
2048
            return 'RTL';
2049 2
        } elseif ($c >= 0xfb1d) {
2050 2
            if ($c === 0xfb1d ||
2051 2
                ($c >= 0xfb1f && $c <= 0xfb28) ||
2052 2
                ($c >= 0xfb2a && $c <= 0xfb36) ||
2053 2
                ($c >= 0xfb38 && $c <= 0xfb3c) ||
2054 2
                $c === 0xfb3e ||
2055 2
                ($c >= 0xfb40 && $c <= 0xfb41) ||
2056 2
                ($c >= 0xfb43 && $c <= 0xfb44) ||
2057 2
                ($c >= 0xfb46 && $c <= 0xfbc1) ||
2058 2
                ($c >= 0xfbd3 && $c <= 0xfd3d) ||
2059 2
                ($c >= 0xfd50 && $c <= 0xfd8f) ||
2060 2
                ($c >= 0xfd92 && $c <= 0xfdc7) ||
2061 2
                ($c >= 0xfdf0 && $c <= 0xfdfc) ||
2062 2
                ($c >= 0xfe70 && $c <= 0xfe74) ||
2063 2
                ($c >= 0xfe76 && $c <= 0xfefc) ||
2064 2
                ($c >= 0x10800 && $c <= 0x10805) ||
2065 2
                $c === 0x10808 ||
2066 2
                ($c >= 0x1080a && $c <= 0x10835) ||
2067 2
                ($c >= 0x10837 && $c <= 0x10838) ||
2068 2
                $c === 0x1083c ||
2069 2
                ($c >= 0x1083f && $c <= 0x10855) ||
2070 2
                ($c >= 0x10857 && $c <= 0x1085f) ||
2071 2
                ($c >= 0x10900 && $c <= 0x1091b) ||
2072 2
                ($c >= 0x10920 && $c <= 0x10939) ||
2073 2
                $c === 0x1093f ||
2074 2
                $c === 0x10a00 ||
2075 2
                ($c >= 0x10a10 && $c <= 0x10a13) ||
2076 2
                ($c >= 0x10a15 && $c <= 0x10a17) ||
2077 2
                ($c >= 0x10a19 && $c <= 0x10a33) ||
2078 2
                ($c >= 0x10a40 && $c <= 0x10a47) ||
2079 2
                ($c >= 0x10a50 && $c <= 0x10a58) ||
2080 2
                ($c >= 0x10a60 && $c <= 0x10a7f) ||
2081 2
                ($c >= 0x10b00 && $c <= 0x10b35) ||
2082 2
                ($c >= 0x10b40 && $c <= 0x10b55) ||
2083 2
                ($c >= 0x10b58 && $c <= 0x10b72) ||
2084 2
                ($c >= 0x10b78 && $c <= 0x10b7f)
2085
            ) {
2086 2
                return 'RTL';
2087
            }
2088
        }
2089
2090 2
        return 'LTR';
2091
    }
2092
2093
    /**
2094
     * Check for php-support.
2095
     *
2096
     * @param string|null $key
2097
     *
2098
     * @return mixed
2099
     *               Return the full support-"array", if $key === null<br>
2100
     *               return bool-value, if $key is used and available<br>
2101
     *               otherwise return <strong>null</strong>
2102
     */
2103 27
    public static function getSupportInfo(string $key = null)
2104
    {
2105 27
        if ($key === null) {
2106 4
            return self::$SUPPORT;
2107
        }
2108
2109 25
        if (self::$INTL_TRANSLITERATOR_LIST === null) {
2110 1
            self::$INTL_TRANSLITERATOR_LIST = self::getData('transliterator_list');
2111
        }
2112
        // compatibility fix for old versions
2113 25
        self::$SUPPORT['intl__transliterator_list_ids'] = self::$INTL_TRANSLITERATOR_LIST;
2114
2115 25
        return self::$SUPPORT[$key] ?? null;
2116
    }
2117
2118
    /**
2119
     * Warning: this method only works for some file-types (png, jpg)
2120
     *          if you need more supported types, please use e.g. "finfo"
2121
     *
2122
     * @param string $str
2123
     * @param array  $fallback with this keys: 'ext', 'mime', 'type'
2124
     *
2125
     * @return array
2126
     *               with this keys: 'ext', 'mime', 'type'
2127
     */
2128 39
    public static function get_file_type(
2129
        string $str,
2130
        array $fallback = [
2131
            'ext'  => null,
2132
            'mime' => 'application/octet-stream',
2133
            'type' => null,
2134
        ]
2135
    ): array {
2136 39
        if ($str === '') {
2137
            return $fallback;
2138
        }
2139
2140
        /** @var string|false $str_info - needed for PhpStan (stubs error) */
2141 39
        $str_info = \substr($str, 0, 2);
2142 39
        if ($str_info === false || \strlen($str_info) !== 2) {
2143 11
            return $fallback;
2144
        }
2145
2146
        // DEBUG
2147
        //var_dump($str_info);
2148
2149
        /** @var array|false $str_info - needed for PhpStan (stubs error) */
2150 35
        $str_info = \unpack('C2chars', $str_info);
0 ignored issues
show
Bug introduced by
$str_info of type array|false is incompatible with the type string expected by parameter $data of unpack(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2150
        $str_info = \unpack('C2chars', /** @scrutinizer ignore-type */ $str_info);
Loading history...
2151 35
        if ($str_info === false) {
2152
            return $fallback;
2153
        }
2154
        /** @noinspection OffsetOperationsInspection */
2155 35
        $type_code = (int) ($str_info['chars1'] . $str_info['chars2']);
2156
2157
        // DEBUG
2158
        //var_dump($type_code);
2159
2160
        //
2161
        // info: https://en.wikipedia.org/wiki/Magic_number_%28programming%29#Format_indicator
2162
        //
2163
        switch ($type_code) {
2164
            // WARNING: do not add too simple comparisons, because of false-positive results:
2165
            //
2166
            // 3780 => 'pdf', 7790 => 'exe', 7784 => 'midi', 8075 => 'zip',
2167
            // 8297 => 'rar', 7173 => 'gif', 7373 => 'tiff' 6677 => 'bmp', ...
2168
            //
2169 35
            case 255216:
2170
                $ext = 'jpg';
2171
                $mime = 'image/jpeg';
2172
                $type = 'binary';
2173
2174
                break;
2175 35
            case 13780:
2176 7
                $ext = 'png';
2177 7
                $mime = 'image/png';
2178 7
                $type = 'binary';
2179
2180 7
                break;
2181
            default:
2182 34
                return $fallback;
2183
        }
2184
2185
        return [
2186 7
            'ext'  => $ext,
2187 7
            'mime' => $mime,
2188 7
            'type' => $type,
2189
        ];
2190
    }
2191
2192
    /**
2193
     * @param int    $length         <p>Length of the random string.</p>
2194
     * @param string $possible_chars [optional] <p>Characters string for the random selection.</p>
2195
     * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
2196
     *
2197
     * @return string
2198
     */
2199 1
    public static function get_random_string(
2200
        int $length,
2201
        string $possible_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
2202
        string $encoding = 'UTF-8'
2203
    ): string {
2204
        // init
2205 1
        $i = 0;
2206 1
        $str = '';
2207
2208
        //
2209
        // add random chars
2210
        //
2211
2212 1
        if ($encoding === 'UTF-8') {
2213 1
            $max_length = (int) \mb_strlen($possible_chars);
2214 1
            if ($max_length === 0) {
2215 1
                return '';
2216
            }
2217
2218 1
            while ($i < $length) {
2219
                try {
2220 1
                    $rand_int = \random_int(0, $max_length - 1);
2221
                } catch (\Exception $e) {
2222
                    /** @noinspection RandomApiMigrationInspection */
2223
                    $rand_int = \mt_rand(0, $max_length - 1);
2224
                }
2225 1
                $char = \mb_substr($possible_chars, $rand_int, 1);
2226 1
                if ($char !== false) {
2227 1
                    $str .= $char;
2228 1
                    ++$i;
2229
                }
2230
            }
2231
        } else {
2232
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
2233
2234
            $max_length = (int) self::strlen($possible_chars, $encoding);
2235
            if ($max_length === 0) {
2236
                return '';
2237
            }
2238
2239
            while ($i < $length) {
2240
                try {
2241
                    $rand_int = \random_int(0, $max_length - 1);
2242
                } catch (\Exception $e) {
2243
                    /** @noinspection RandomApiMigrationInspection */
2244
                    $rand_int = \mt_rand(0, $max_length - 1);
2245
                }
2246
                $char = self::substr($possible_chars, $rand_int, 1, $encoding);
2247
                if ($char !== false) {
2248
                    $str .= $char;
2249
                    ++$i;
2250
                }
2251
            }
2252
        }
2253
2254 1
        return $str;
2255
    }
2256
2257
    /**
2258
     * @param int|string $entropy_extra [optional] <p>Extra entropy via a string or int value.</p>
2259
     * @param bool       $use_md5       [optional] <p>Return the unique identifier as md5-hash? Default: true</p>
2260
     *
2261
     * @return string
2262
     */
2263 1
    public static function get_unique_string($entropy_extra = '', bool $use_md5 = true): string
2264
    {
2265 1
        $unique_helper = \random_int(0, \mt_getrandmax()) .
2266 1
                        \session_id() .
2267 1
                        ($_SERVER['REMOTE_ADDR'] ?? '') .
2268 1
                        ($_SERVER['SERVER_ADDR'] ?? '') .
2269 1
                        $entropy_extra;
2270
2271 1
        $unique_string = \uniqid($unique_helper, true);
2272
2273 1
        if ($use_md5) {
2274 1
            $unique_string = \md5($unique_string . $unique_helper);
2275
        }
2276
2277 1
        return $unique_string;
2278
    }
2279
2280
    /**
2281
     * alias for "UTF8::string_has_bom()"
2282
     *
2283
     * @param string $str
2284
     *
2285
     * @return bool
2286
     *
2287
     * @see UTF8::string_has_bom()
2288
     * @deprecated <p>please use "UTF8::string_has_bom()"</p>
2289
     */
2290 2
    public static function hasBom(string $str): bool
2291
    {
2292 2
        return self::string_has_bom($str);
2293
    }
2294
2295
    /**
2296
     * Returns true if the string contains a lower case char, false otherwise.
2297
     *
2298
     * @param string $str <p>The input string.</p>
2299
     *
2300
     * @return bool whether or not the string contains a lower case character
2301
     */
2302 47
    public static function has_lowercase(string $str): bool
2303
    {
2304 47
        if (self::$SUPPORT['mbstring'] === true) {
2305
            /** @noinspection PhpComposerExtensionStubsInspection */
2306 47
            return \mb_ereg_match('.*[[:lower:]]', $str);
2307
        }
2308
2309
        return self::str_matches_pattern($str, '.*[[:lower:]]');
2310
    }
2311
2312
    /**
2313
     * Returns true if the string contains an upper case char, false otherwise.
2314
     *
2315
     * @param string $str <p>The input string.</p>
2316
     *
2317
     * @return bool whether or not the string contains an upper case character
2318
     */
2319 12
    public static function has_uppercase(string $str): bool
2320
    {
2321 12
        if (self::$SUPPORT['mbstring'] === true) {
2322
            /** @noinspection PhpComposerExtensionStubsInspection */
2323 12
            return \mb_ereg_match('.*[[:upper:]]', $str);
2324
        }
2325
2326
        return self::str_matches_pattern($str, '.*[[:upper:]]');
2327
    }
2328
2329
    /**
2330
     * Converts a hexadecimal value into a UTF-8 character.
2331
     *
2332
     * @param string $hexdec <p>The hexadecimal value.</p>
2333
     *
2334
     * @return false|string one single UTF-8 character
2335
     */
2336 4
    public static function hex_to_chr(string $hexdec)
2337
    {
2338 4
        return self::decimal_to_chr(\hexdec($hexdec));
2339
    }
2340
2341
    /**
2342
     * Converts hexadecimal U+xxxx code point representation to integer.
2343
     *
2344
     * INFO: opposite to UTF8::int_to_hex()
2345
     *
2346
     * @param string $hexdec <p>The hexadecimal code point representation.</p>
2347
     *
2348
     * @return false|int the code point, or false on failure
2349
     */
2350 2
    public static function hex_to_int($hexdec)
2351
    {
2352
        // init
2353 2
        $hexdec = (string) $hexdec;
2354
2355 2
        if ($hexdec === '') {
2356 2
            return false;
2357
        }
2358
2359 2
        if (\preg_match('/^(?:\\\u|U\+|)([a-zA-Z0-9]{4,6})$/', $hexdec, $match)) {
2360 2
            return \intval($match[1], 16);
2361
        }
2362
2363 2
        return false;
2364
    }
2365
2366
    /**
2367
     * alias for "UTF8::html_entity_decode()"
2368
     *
2369
     * @param string $str
2370
     * @param int    $flags
2371
     * @param string $encoding
2372
     *
2373
     * @return string
2374
     *
2375
     * @see UTF8::html_entity_decode()
2376
     * @deprecated <p>please use "UTF8::html_entity_decode()"</p>
2377
     */
2378 2
    public static function html_decode(
2379
        string $str,
2380
        int $flags = null,
2381
        string $encoding = 'UTF-8'
2382
    ): string {
2383 2
        return self::html_entity_decode($str, $flags, $encoding);
2384
    }
2385
2386
    /**
2387
     * Converts a UTF-8 string to a series of HTML numbered entities.
2388
     *
2389
     * INFO: opposite to UTF8::html_decode()
2390
     *
2391
     * @param string $str              <p>The Unicode string to be encoded as numbered entities.</p>
2392
     * @param bool   $keep_ascii_chars [optional] <p>Keep ASCII chars.</p>
2393
     * @param string $encoding         [optional] <p>Set the charset for e.g. "mb_" function</p>
2394
     *
2395
     * @return string HTML numbered entities
2396
     */
2397 14
    public static function html_encode(
2398
        string $str,
2399
        bool $keep_ascii_chars = false,
2400
        string $encoding = 'UTF-8'
2401
    ): string {
2402 14
        if ($str === '') {
2403 4
            return '';
2404
        }
2405
2406 14
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2407 4
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
2408
        }
2409
2410
        // INFO: http://stackoverflow.com/questions/35854535/better-explanation-of-convmap-in-mb-encode-numericentity
2411 14
        if (self::$SUPPORT['mbstring'] === true) {
2412 14
            $start_code = 0x00;
2413 14
            if ($keep_ascii_chars === true) {
2414 13
                $start_code = 0x80;
2415
            }
2416
2417 14
            if ($encoding === 'UTF-8') {
2418
                /** @var false|string|null $return - needed for PhpStan (stubs error) */
2419 14
                $return = \mb_encode_numericentity(
2420 14
                    $str,
2421 14
                    [$start_code, 0xfffff, 0, 0xfffff, 0]
2422
                );
2423 14
                if ($return !== null && $return !== false) {
2424 14
                    return $return;
2425
                }
2426
            }
2427
2428
            /** @var false|string|null $return - needed for PhpStan (stubs error) */
2429 4
            $return = \mb_encode_numericentity(
2430 4
                $str,
2431 4
                [$start_code, 0xfffff, 0, 0xfffff, 0],
2432 4
                $encoding
2433
            );
2434 4
            if ($return !== null && $return !== false) {
2435 4
                return $return;
2436
            }
2437
        }
2438
2439
        //
2440
        // fallback via vanilla php
2441
        //
2442
2443
        return \implode(
2444
            '',
2445
            \array_map(
2446
                static function (string $chr) use ($keep_ascii_chars, $encoding): string {
2447
                    return self::single_chr_html_encode($chr, $keep_ascii_chars, $encoding);
2448
                },
2449
                self::str_split($str)
2450
            )
2451
        );
2452
    }
2453
2454
    /**
2455
     * UTF-8 version of html_entity_decode()
2456
     *
2457
     * The reason we are not using html_entity_decode() by itself is because
2458
     * while it is not technically correct to leave out the semicolon
2459
     * at the end of an entity most browsers will still interpret the entity
2460
     * correctly. html_entity_decode() does not convert entities without
2461
     * semicolons, so we are left with our own little solution here. Bummer.
2462
     *
2463
     * Convert all HTML entities to their applicable characters
2464
     *
2465
     * INFO: opposite to UTF8::html_encode()
2466
     *
2467
     * @see http://php.net/manual/en/function.html-entity-decode.php
2468
     *
2469
     * @param string $str      <p>
2470
     *                         The input string.
2471
     *                         </p>
2472
     * @param int    $flags    [optional] <p>
2473
     *                         A bitmask of one or more of the following flags, which specify how to handle quotes
2474
     *                         and which document type to use. The default is ENT_COMPAT | ENT_HTML401.
2475
     *                         <table>
2476
     *                         Available <i>flags</i> constants
2477
     *                         <tr valign="top">
2478
     *                         <td>Constant Name</td>
2479
     *                         <td>Description</td>
2480
     *                         </tr>
2481
     *                         <tr valign="top">
2482
     *                         <td><b>ENT_COMPAT</b></td>
2483
     *                         <td>Will convert double-quotes and leave single-quotes alone.</td>
2484
     *                         </tr>
2485
     *                         <tr valign="top">
2486
     *                         <td><b>ENT_QUOTES</b></td>
2487
     *                         <td>Will convert both double and single quotes.</td>
2488
     *                         </tr>
2489
     *                         <tr valign="top">
2490
     *                         <td><b>ENT_NOQUOTES</b></td>
2491
     *                         <td>Will leave both double and single quotes unconverted.</td>
2492
     *                         </tr>
2493
     *                         <tr valign="top">
2494
     *                         <td><b>ENT_HTML401</b></td>
2495
     *                         <td>
2496
     *                         Handle code as HTML 4.01.
2497
     *                         </td>
2498
     *                         </tr>
2499
     *                         <tr valign="top">
2500
     *                         <td><b>ENT_XML1</b></td>
2501
     *                         <td>
2502
     *                         Handle code as XML 1.
2503
     *                         </td>
2504
     *                         </tr>
2505
     *                         <tr valign="top">
2506
     *                         <td><b>ENT_XHTML</b></td>
2507
     *                         <td>
2508
     *                         Handle code as XHTML.
2509
     *                         </td>
2510
     *                         </tr>
2511
     *                         <tr valign="top">
2512
     *                         <td><b>ENT_HTML5</b></td>
2513
     *                         <td>
2514
     *                         Handle code as HTML 5.
2515
     *                         </td>
2516
     *                         </tr>
2517
     *                         </table>
2518
     *                         </p>
2519
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
2520
     *
2521
     * @return string the decoded string
2522
     */
2523 46
    public static function html_entity_decode(
2524
        string $str,
2525
        int $flags = null,
2526
        string $encoding = 'UTF-8'
2527
    ): string {
2528
        if (
2529 46
            !isset($str[3]) // examples: &; || &x;
2530
            ||
2531 46
            \strpos($str, '&') === false // no "&"
2532
        ) {
2533 23
            return $str;
2534
        }
2535
2536 44
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2537 9
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
2538
        }
2539
2540 44
        if ($flags === null) {
2541 10
            $flags = \ENT_QUOTES | \ENT_HTML5;
2542
        }
2543
2544
        if (
2545 44
            $encoding !== 'UTF-8'
2546
            &&
2547 44
            $encoding !== 'ISO-8859-1'
2548
            &&
2549 44
            $encoding !== 'WINDOWS-1252'
2550
            &&
2551 44
            self::$SUPPORT['mbstring'] === false
2552
        ) {
2553
            \trigger_error('UTF8::html_entity_decode() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
2554
        }
2555
2556
        do {
2557 44
            $str_compare = $str;
2558
2559
            // INFO: http://stackoverflow.com/questions/35854535/better-explanation-of-convmap-in-mb-encode-numericentity
2560 44
            if (self::$SUPPORT['mbstring'] === true) {
2561 44
                if ($encoding === 'UTF-8') {
2562
                    /** @var false|string|null $strTmp - needed for PhpStan (stubs error) */
2563 44
                    $strTmp = \mb_decode_numericentity(
2564 44
                        $str,
2565 44
                        [0x80, 0xfffff, 0, 0xfffff, 0]
2566
                    );
2567
                } else {
2568
                    /** @var false|string|null $strTmp - needed for PhpStan (stubs error) */
2569 4
                    $strTmp = \mb_decode_numericentity(
2570 4
                        $str,
2571 4
                        [0x80, 0xfffff, 0, 0xfffff, 0],
2572 4
                        $encoding
2573
                    );
2574
                }
2575 44
                if ($strTmp === null || $strTmp === false) {
2576 44
                    $str = self::html_entity_decode_helper($str, $encoding);
2577
                }
2578
            } else {
2579
                $str = self::html_entity_decode_helper($str, $encoding);
2580
            }
2581
2582 44
            if (\strpos($str, '&') !== false) {
2583 44
                if (\strpos($str, '&#') !== false) {
2584
                    // decode also numeric & UTF16 two byte entities
2585 36
                    $str = (string) \preg_replace(
2586 36
                        '/(&#(?:x0*[0-9a-fA-F]{2,6}(?![0-9a-fA-F;])|(?:0*\d{2,6}(?![0-9;]))))/S',
2587 36
                        '$1;',
2588 36
                        $str
2589
                    );
2590
                }
2591
2592 44
                $str = \html_entity_decode(
2593 44
                    $str,
2594 44
                    $flags,
2595 44
                    $encoding
2596
                );
2597
            }
2598 44
        } while ($str_compare !== $str);
2599
2600 44
        return $str;
2601
    }
2602
2603
    /**
2604
     * Create a escape html version of the string via "UTF8::htmlspecialchars()".
2605
     *
2606
     * @param string $str
2607
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
2608
     *
2609
     * @return string
2610
     */
2611 6
    public static function html_escape(string $str, string $encoding = 'UTF-8'): string
2612
    {
2613 6
        return self::htmlspecialchars(
2614 6
            $str,
2615 6
            \ENT_QUOTES | \ENT_SUBSTITUTE,
2616 6
            $encoding
2617
        );
2618
    }
2619
2620
    /**
2621
     * Remove empty html-tag.
2622
     *
2623
     * e.g.: <tag></tag>
2624
     *
2625
     * @param string $str
2626
     *
2627
     * @return string
2628
     */
2629 1
    public static function html_stripe_empty_tags(string $str): string
2630
    {
2631 1
        return (string) \preg_replace(
2632 1
            '/<[^\\/>]*?>\\s*?<\\/[^>]*?>/u',
2633 1
            '',
2634 1
            $str
2635
        );
2636
    }
2637
2638
    /**
2639
     * Convert all applicable characters to HTML entities: UTF-8 version of htmlentities()
2640
     *
2641
     * @see http://php.net/manual/en/function.htmlentities.php
2642
     *
2643
     * @param string $str           <p>
2644
     *                              The input string.
2645
     *                              </p>
2646
     * @param int    $flags         [optional] <p>
2647
     *                              A bitmask of one or more of the following flags, which specify how to handle
2648
     *                              quotes, invalid code unit sequences and the used document type. The default is
2649
     *                              ENT_COMPAT | ENT_HTML401.
2650
     *                              <table>
2651
     *                              Available <i>flags</i> constants
2652
     *                              <tr valign="top">
2653
     *                              <td>Constant Name</td>
2654
     *                              <td>Description</td>
2655
     *                              </tr>
2656
     *                              <tr valign="top">
2657
     *                              <td><b>ENT_COMPAT</b></td>
2658
     *                              <td>Will convert double-quotes and leave single-quotes alone.</td>
2659
     *                              </tr>
2660
     *                              <tr valign="top">
2661
     *                              <td><b>ENT_QUOTES</b></td>
2662
     *                              <td>Will convert both double and single quotes.</td>
2663
     *                              </tr>
2664
     *                              <tr valign="top">
2665
     *                              <td><b>ENT_NOQUOTES</b></td>
2666
     *                              <td>Will leave both double and single quotes unconverted.</td>
2667
     *                              </tr>
2668
     *                              <tr valign="top">
2669
     *                              <td><b>ENT_IGNORE</b></td>
2670
     *                              <td>
2671
     *                              Silently discard invalid code unit sequences instead of returning
2672
     *                              an empty string. Using this flag is discouraged as it
2673
     *                              may have security implications.
2674
     *                              </td>
2675
     *                              </tr>
2676
     *                              <tr valign="top">
2677
     *                              <td><b>ENT_SUBSTITUTE</b></td>
2678
     *                              <td>
2679
     *                              Replace invalid code unit sequences with a Unicode Replacement Character
2680
     *                              U+FFFD (UTF-8) or &#38;#38;#FFFD; (otherwise) instead of returning an empty
2681
     *                              string.
2682
     *                              </td>
2683
     *                              </tr>
2684
     *                              <tr valign="top">
2685
     *                              <td><b>ENT_DISALLOWED</b></td>
2686
     *                              <td>
2687
     *                              Replace invalid code points for the given document type with a
2688
     *                              Unicode Replacement Character U+FFFD (UTF-8) or &#38;#38;#FFFD;
2689
     *                              (otherwise) instead of leaving them as is. This may be useful, for
2690
     *                              instance, to ensure the well-formedness of XML documents with
2691
     *                              embedded external content.
2692
     *                              </td>
2693
     *                              </tr>
2694
     *                              <tr valign="top">
2695
     *                              <td><b>ENT_HTML401</b></td>
2696
     *                              <td>
2697
     *                              Handle code as HTML 4.01.
2698
     *                              </td>
2699
     *                              </tr>
2700
     *                              <tr valign="top">
2701
     *                              <td><b>ENT_XML1</b></td>
2702
     *                              <td>
2703
     *                              Handle code as XML 1.
2704
     *                              </td>
2705
     *                              </tr>
2706
     *                              <tr valign="top">
2707
     *                              <td><b>ENT_XHTML</b></td>
2708
     *                              <td>
2709
     *                              Handle code as XHTML.
2710
     *                              </td>
2711
     *                              </tr>
2712
     *                              <tr valign="top">
2713
     *                              <td><b>ENT_HTML5</b></td>
2714
     *                              <td>
2715
     *                              Handle code as HTML 5.
2716
     *                              </td>
2717
     *                              </tr>
2718
     *                              </table>
2719
     *                              </p>
2720
     * @param string $encoding      [optional] <p>
2721
     *                              Like <b>htmlspecialchars</b>,
2722
     *                              <b>htmlentities</b> takes an optional third argument
2723
     *                              <i>encoding</i> which defines encoding used in
2724
     *                              conversion.
2725
     *                              Although this argument is technically optional, you are highly
2726
     *                              encouraged to specify the correct value for your code.
2727
     *                              </p>
2728
     * @param bool   $double_encode [optional] <p>
2729
     *                              When <i>double_encode</i> is turned off PHP will not
2730
     *                              encode existing html entities. The default is to convert everything.
2731
     *                              </p>
2732
     *
2733
     * @return string
2734
     *                <p>
2735
     *                The encoded string.
2736
     *                <br><br>
2737
     *                If the input <i>string</i> contains an invalid code unit
2738
     *                sequence within the given <i>encoding</i> an empty string
2739
     *                will be returned, unless either the <b>ENT_IGNORE</b> or
2740
     *                <b>ENT_SUBSTITUTE</b> flags are set.
2741
     *                </p>
2742
     */
2743 9
    public static function htmlentities(
2744
        string $str,
2745
        int $flags = \ENT_COMPAT,
2746
        string $encoding = 'UTF-8',
2747
        bool $double_encode = true
2748
    ): string {
2749 9
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2750 7
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
2751
        }
2752
2753 9
        $str = \htmlentities(
2754 9
            $str,
2755 9
            $flags,
2756 9
            $encoding,
2757 9
            $double_encode
2758
        );
2759
2760
        /**
2761
         * PHP doesn't replace a backslash to its html entity since this is something
2762
         * that's mostly used to escape characters when inserting in a database. Since
2763
         * we're using a decent database layer, we don't need this shit and we're replacing
2764
         * the double backslashes by its' html entity equivalent.
2765
         *
2766
         * https://github.com/forkcms/library/blob/master/spoon/filter/filter.php#L303
2767
         */
2768 9
        $str = \str_replace('\\', '&#92;', $str);
2769
2770 9
        return self::html_encode($str, true, $encoding);
2771
    }
2772
2773
    /**
2774
     * Convert only special characters to HTML entities: UTF-8 version of htmlspecialchars()
2775
     *
2776
     * INFO: Take a look at "UTF8::htmlentities()"
2777
     *
2778
     * @see http://php.net/manual/en/function.htmlspecialchars.php
2779
     *
2780
     * @param string $str           <p>
2781
     *                              The string being converted.
2782
     *                              </p>
2783
     * @param int    $flags         [optional] <p>
2784
     *                              A bitmask of one or more of the following flags, which specify how to handle
2785
     *                              quotes, invalid code unit sequences and the used document type. The default is
2786
     *                              ENT_COMPAT | ENT_HTML401.
2787
     *                              <table>
2788
     *                              Available <i>flags</i> constants
2789
     *                              <tr valign="top">
2790
     *                              <td>Constant Name</td>
2791
     *                              <td>Description</td>
2792
     *                              </tr>
2793
     *                              <tr valign="top">
2794
     *                              <td><b>ENT_COMPAT</b></td>
2795
     *                              <td>Will convert double-quotes and leave single-quotes alone.</td>
2796
     *                              </tr>
2797
     *                              <tr valign="top">
2798
     *                              <td><b>ENT_QUOTES</b></td>
2799
     *                              <td>Will convert both double and single quotes.</td>
2800
     *                              </tr>
2801
     *                              <tr valign="top">
2802
     *                              <td><b>ENT_NOQUOTES</b></td>
2803
     *                              <td>Will leave both double and single quotes unconverted.</td>
2804
     *                              </tr>
2805
     *                              <tr valign="top">
2806
     *                              <td><b>ENT_IGNORE</b></td>
2807
     *                              <td>
2808
     *                              Silently discard invalid code unit sequences instead of returning
2809
     *                              an empty string. Using this flag is discouraged as it
2810
     *                              may have security implications.
2811
     *                              </td>
2812
     *                              </tr>
2813
     *                              <tr valign="top">
2814
     *                              <td><b>ENT_SUBSTITUTE</b></td>
2815
     *                              <td>
2816
     *                              Replace invalid code unit sequences with a Unicode Replacement Character
2817
     *                              U+FFFD (UTF-8) or &#38;#38;#FFFD; (otherwise) instead of returning an empty
2818
     *                              string.
2819
     *                              </td>
2820
     *                              </tr>
2821
     *                              <tr valign="top">
2822
     *                              <td><b>ENT_DISALLOWED</b></td>
2823
     *                              <td>
2824
     *                              Replace invalid code points for the given document type with a
2825
     *                              Unicode Replacement Character U+FFFD (UTF-8) or &#38;#38;#FFFD;
2826
     *                              (otherwise) instead of leaving them as is. This may be useful, for
2827
     *                              instance, to ensure the well-formedness of XML documents with
2828
     *                              embedded external content.
2829
     *                              </td>
2830
     *                              </tr>
2831
     *                              <tr valign="top">
2832
     *                              <td><b>ENT_HTML401</b></td>
2833
     *                              <td>
2834
     *                              Handle code as HTML 4.01.
2835
     *                              </td>
2836
     *                              </tr>
2837
     *                              <tr valign="top">
2838
     *                              <td><b>ENT_XML1</b></td>
2839
     *                              <td>
2840
     *                              Handle code as XML 1.
2841
     *                              </td>
2842
     *                              </tr>
2843
     *                              <tr valign="top">
2844
     *                              <td><b>ENT_XHTML</b></td>
2845
     *                              <td>
2846
     *                              Handle code as XHTML.
2847
     *                              </td>
2848
     *                              </tr>
2849
     *                              <tr valign="top">
2850
     *                              <td><b>ENT_HTML5</b></td>
2851
     *                              <td>
2852
     *                              Handle code as HTML 5.
2853
     *                              </td>
2854
     *                              </tr>
2855
     *                              </table>
2856
     *                              </p>
2857
     * @param string $encoding      [optional] <p>
2858
     *                              Defines encoding used in conversion.
2859
     *                              </p>
2860
     *                              <p>
2861
     *                              For the purposes of this function, the encodings
2862
     *                              ISO-8859-1, ISO-8859-15,
2863
     *                              UTF-8, cp866,
2864
     *                              cp1251, cp1252, and
2865
     *                              KOI8-R are effectively equivalent, provided the
2866
     *                              <i>string</i> itself is valid for the encoding, as
2867
     *                              the characters affected by <b>htmlspecialchars</b> occupy
2868
     *                              the same positions in all of these encodings.
2869
     *                              </p>
2870
     * @param bool   $double_encode [optional] <p>
2871
     *                              When <i>double_encode</i> is turned off PHP will not
2872
     *                              encode existing html entities, the default is to convert everything.
2873
     *                              </p>
2874
     *
2875
     * @return string the converted string.
2876
     *                </p>
2877
     *                <p>
2878
     *                If the input <i>string</i> contains an invalid code unit
2879
     *                sequence within the given <i>encoding</i> an empty string
2880
     *                will be returned, unless either the <b>ENT_IGNORE</b> or
2881
     *                <b>ENT_SUBSTITUTE</b> flags are set
2882
     */
2883 8
    public static function htmlspecialchars(
2884
        string $str,
2885
        int $flags = \ENT_COMPAT,
2886
        string $encoding = 'UTF-8',
2887
        bool $double_encode = true
2888
    ): string {
2889 8
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2890 8
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
2891
        }
2892
2893 8
        return \htmlspecialchars(
2894 8
            $str,
2895 8
            $flags,
2896 8
            $encoding,
2897 8
            $double_encode
2898
        );
2899
    }
2900
2901
    /**
2902
     * Checks whether iconv is available on the server.
2903
     *
2904
     * @return bool
2905
     *              <strong>true</strong> if available, <strong>false</strong> otherwise
2906
     */
2907
    public static function iconv_loaded(): bool
2908
    {
2909
        return \extension_loaded('iconv');
2910
    }
2911
2912
    /**
2913
     * alias for "UTF8::decimal_to_chr()"
2914
     *
2915
     * @param mixed $int
2916
     *
2917
     * @return string
2918
     *
2919
     * @see UTF8::decimal_to_chr()
2920
     * @deprecated <p>please use "UTF8::decimal_to_chr()"</p>
2921
     */
2922 4
    public static function int_to_chr($int): string
2923
    {
2924 4
        return self::decimal_to_chr($int);
2925
    }
2926
2927
    /**
2928
     * Converts Integer to hexadecimal U+xxxx code point representation.
2929
     *
2930
     * INFO: opposite to UTF8::hex_to_int()
2931
     *
2932
     * @param int    $int    <p>The integer to be converted to hexadecimal code point.</p>
2933
     * @param string $prefix [optional]
2934
     *
2935
     * @return string the code point, or empty string on failure
2936
     */
2937 6
    public static function int_to_hex(int $int, string $prefix = 'U+'): string
2938
    {
2939 6
        $hex = \dechex($int);
2940
2941 6
        $hex = (\strlen($hex) < 4 ? \substr('0000' . $hex, -4) : $hex);
2942
2943 6
        return $prefix . $hex . '';
2944
    }
2945
2946
    /**
2947
     * Checks whether intl-char is available on the server.
2948
     *
2949
     * @return bool
2950
     *              <strong>true</strong> if available, <strong>false</strong> otherwise
2951
     */
2952
    public static function intlChar_loaded(): bool
2953
    {
2954
        return \class_exists('IntlChar');
2955
    }
2956
2957
    /**
2958
     * Checks whether intl is available on the server.
2959
     *
2960
     * @return bool
2961
     *              <strong>true</strong> if available, <strong>false</strong> otherwise
2962
     */
2963 5
    public static function intl_loaded(): bool
2964
    {
2965 5
        return \extension_loaded('intl');
2966
    }
2967
2968
    /**
2969
     * alias for "UTF8::is_ascii()"
2970
     *
2971
     * @param string $str
2972
     *
2973
     * @return bool
2974
     *
2975
     * @see UTF8::is_ascii()
2976
     * @deprecated <p>please use "UTF8::is_ascii()"</p>
2977
     */
2978 2
    public static function isAscii(string $str): bool
2979
    {
2980 2
        return ASCII::is_ascii($str);
2981
    }
2982
2983
    /**
2984
     * alias for "UTF8::is_base64()"
2985
     *
2986
     * @param string $str
2987
     *
2988
     * @return bool
2989
     *
2990
     * @see UTF8::is_base64()
2991
     * @deprecated <p>please use "UTF8::is_base64()"</p>
2992
     */
2993 2
    public static function isBase64($str): bool
2994
    {
2995 2
        return self::is_base64($str);
2996
    }
2997
2998
    /**
2999
     * alias for "UTF8::is_binary()"
3000
     *
3001
     * @param mixed $str
3002
     * @param bool  $strict
3003
     *
3004
     * @return bool
3005
     *
3006
     * @see UTF8::is_binary()
3007
     * @deprecated <p>please use "UTF8::is_binary()"</p>
3008
     */
3009 4
    public static function isBinary($str, $strict = false): bool
3010
    {
3011 4
        return self::is_binary($str, $strict);
3012
    }
3013
3014
    /**
3015
     * alias for "UTF8::is_bom()"
3016
     *
3017
     * @param string $utf8_chr
3018
     *
3019
     * @return bool
3020
     *
3021
     * @see UTF8::is_bom()
3022
     * @deprecated <p>please use "UTF8::is_bom()"</p>
3023
     */
3024 2
    public static function isBom(string $utf8_chr): bool
3025
    {
3026 2
        return self::is_bom($utf8_chr);
3027
    }
3028
3029
    /**
3030
     * alias for "UTF8::is_html()"
3031
     *
3032
     * @param string $str
3033
     *
3034
     * @return bool
3035
     *
3036
     * @see UTF8::is_html()
3037
     * @deprecated <p>please use "UTF8::is_html()"</p>
3038
     */
3039 2
    public static function isHtml(string $str): bool
3040
    {
3041 2
        return self::is_html($str);
3042
    }
3043
3044
    /**
3045
     * alias for "UTF8::is_json()"
3046
     *
3047
     * @param string $str
3048
     *
3049
     * @return bool
3050
     *
3051
     * @see UTF8::is_json()
3052
     * @deprecated <p>please use "UTF8::is_json()"</p>
3053
     */
3054
    public static function isJson(string $str): bool
3055
    {
3056
        return self::is_json($str);
3057
    }
3058
3059
    /**
3060
     * alias for "UTF8::is_utf16()"
3061
     *
3062
     * @param mixed $str
3063
     *
3064
     * @return false|int
3065
     *                   <strong>false</strong> if is't not UTF16,<br>
3066
     *                   <strong>1</strong> for UTF-16LE,<br>
3067
     *                   <strong>2</strong> for UTF-16BE
3068
     *
3069
     * @see UTF8::is_utf16()
3070
     * @deprecated <p>please use "UTF8::is_utf16()"</p>
3071
     */
3072 2
    public static function isUtf16($str)
3073
    {
3074 2
        return self::is_utf16($str);
3075
    }
3076
3077
    /**
3078
     * alias for "UTF8::is_utf32()"
3079
     *
3080
     * @param mixed $str
3081
     *
3082
     * @return false|int
3083
     *                   <strong>false</strong> if is't not UTF16,
3084
     *                   <strong>1</strong> for UTF-32LE,
3085
     *                   <strong>2</strong> for UTF-32BE
3086
     *
3087
     * @see UTF8::is_utf32()
3088
     * @deprecated <p>please use "UTF8::is_utf32()"</p>
3089
     */
3090 2
    public static function isUtf32($str)
3091
    {
3092 2
        return self::is_utf32($str);
3093
    }
3094
3095
    /**
3096
     * alias for "UTF8::is_utf8()"
3097
     *
3098
     * @param string $str
3099
     * @param bool   $strict
3100
     *
3101
     * @return bool
3102
     *
3103
     * @see UTF8::is_utf8()
3104
     * @deprecated <p>please use "UTF8::is_utf8()"</p>
3105
     */
3106 17
    public static function isUtf8($str, $strict = false): bool
3107
    {
3108 17
        return self::is_utf8($str, $strict);
3109
    }
3110
3111
    /**
3112
     * Returns true if the string contains only alphabetic chars, false otherwise.
3113
     *
3114
     * @param string $str
3115
     *
3116
     * @return bool
3117
     *              Whether or not $str contains only alphabetic chars
3118
     */
3119 10
    public static function is_alpha(string $str): bool
3120
    {
3121 10
        if (self::$SUPPORT['mbstring'] === true) {
3122
            /** @noinspection PhpComposerExtensionStubsInspection */
3123 10
            return \mb_ereg_match('^[[:alpha:]]*$', $str);
3124
        }
3125
3126
        return self::str_matches_pattern($str, '^[[:alpha:]]*$');
3127
    }
3128
3129
    /**
3130
     * Returns true if the string contains only alphabetic and numeric chars, false otherwise.
3131
     *
3132
     * @param string $str
3133
     *
3134
     * @return bool
3135
     *              Whether or not $str contains only alphanumeric chars
3136
     */
3137 13
    public static function is_alphanumeric(string $str): bool
3138
    {
3139 13
        if (self::$SUPPORT['mbstring'] === true) {
3140
            /** @noinspection PhpComposerExtensionStubsInspection */
3141 13
            return \mb_ereg_match('^[[:alnum:]]*$', $str);
3142
        }
3143
3144
        return self::str_matches_pattern($str, '^[[:alnum:]]*$');
3145
    }
3146
3147
    /**
3148
     * Checks if a string is 7 bit ASCII.
3149
     *
3150
     * @param string $str <p>The string to check.</p>
3151
     *
3152
     * @return bool
3153
     *              <strong>true</strong> if it is ASCII<br>
3154
     *              <strong>false</strong> otherwise
3155
     */
3156 8
    public static function is_ascii(string $str): bool
3157
    {
3158 8
        return ASCII::is_ascii($str);
3159
    }
3160
3161
    /**
3162
     * Returns true if the string is base64 encoded, false otherwise.
3163
     *
3164
     * @param mixed|string $str                   <p>The input string.</p>
3165
     * @param bool         $empty_string_is_valid [optional] <p>Is an empty string valid base64 or not?</p>
3166
     *
3167
     * @return bool whether or not $str is base64 encoded
3168
     */
3169 16
    public static function is_base64($str, $empty_string_is_valid = false): bool
3170
    {
3171
        if (
3172 16
            $empty_string_is_valid === false
3173
            &&
3174 16
            $str === ''
3175
        ) {
3176 3
            return false;
3177
        }
3178
3179
        /**
3180
         * @psalm-suppress RedundantConditionGivenDocblockType
3181
         */
3182 15
        if (\is_string($str) === false) {
3183 2
            return false;
3184
        }
3185
3186 15
        $base64String = \base64_decode($str, true);
3187
3188 15
        return $base64String !== false && \base64_encode($base64String) === $str;
3189
    }
3190
3191
    /**
3192
     * Check if the input is binary... (is look like a hack).
3193
     *
3194
     * @param mixed $input
3195
     * @param bool  $strict
3196
     *
3197
     * @return bool
3198
     */
3199 39
    public static function is_binary($input, bool $strict = false): bool
3200
    {
3201 39
        $input = (string) $input;
3202 39
        if ($input === '') {
3203 10
            return false;
3204
        }
3205
3206 39
        if (\preg_match('~^[01]+$~', $input)) {
3207 13
            return true;
3208
        }
3209
3210 39
        $ext = self::get_file_type($input);
3211 39
        if ($ext['type'] === 'binary') {
3212 7
            return true;
3213
        }
3214
3215 38
        $test_length = \strlen($input);
3216 38
        $test_null_counting = \substr_count($input, "\x0", 0, $test_length);
3217 38
        if (($test_null_counting / $test_length) > 0.25) {
3218 15
            return true;
3219
        }
3220
3221 34
        if ($strict === true) {
3222 34
            if (self::$SUPPORT['finfo'] === false) {
3223
                throw new \RuntimeException('ext-fileinfo: is not installed');
3224
            }
3225
3226
            /** @noinspection PhpComposerExtensionStubsInspection */
3227 34
            $finfo_encoding = (new \finfo(\FILEINFO_MIME_ENCODING))->buffer($input);
3228 34
            if ($finfo_encoding && $finfo_encoding === 'binary') {
3229 15
                return true;
3230
            }
3231
        }
3232
3233 30
        return false;
3234
    }
3235
3236
    /**
3237
     * Check if the file is binary.
3238
     *
3239
     * @param string $file
3240
     *
3241
     * @return bool
3242
     */
3243 6
    public static function is_binary_file($file): bool
3244
    {
3245
        // init
3246 6
        $block = '';
3247
3248 6
        $fp = \fopen($file, 'rb');
3249 6
        if (\is_resource($fp)) {
3250 6
            $block = \fread($fp, 512);
3251 6
            \fclose($fp);
3252
        }
3253
3254 6
        if ($block === '') {
3255 2
            return false;
3256
        }
3257
3258 6
        return self::is_binary($block, true);
3259
    }
3260
3261
    /**
3262
     * Returns true if the string contains only whitespace chars, false otherwise.
3263
     *
3264
     * @param string $str
3265
     *
3266
     * @return bool
3267
     *              Whether or not $str contains only whitespace characters
3268
     */
3269 15
    public static function is_blank(string $str): bool
3270
    {
3271 15
        if (self::$SUPPORT['mbstring'] === true) {
3272
            /** @noinspection PhpComposerExtensionStubsInspection */
3273 15
            return \mb_ereg_match('^[[:space:]]*$', $str);
3274
        }
3275
3276
        return self::str_matches_pattern($str, '^[[:space:]]*$');
3277
    }
3278
3279
    /**
3280
     * Checks if the given string is equal to any "Byte Order Mark".
3281
     *
3282
     * WARNING: Use "UTF8::string_has_bom()" if you will check BOM in a string.
3283
     *
3284
     * @param string $str <p>The input string.</p>
3285
     *
3286
     * @return bool
3287
     *              <strong>true</strong> if the $utf8_chr is Byte Order Mark, <strong>false</strong> otherwise
3288
     */
3289 2
    public static function is_bom($str): bool
3290
    {
3291
        /** @noinspection PhpUnusedLocalVariableInspection */
3292 2
        foreach (self::$BOM as $bom_string => &$bom_byte_length) {
3293 2
            if ($str === $bom_string) {
3294 2
                return true;
3295
            }
3296
        }
3297
3298 2
        return false;
3299
    }
3300
3301
    /**
3302
     * Determine whether the string is considered to be empty.
3303
     *
3304
     * A variable is considered empty if it does not exist or if its value equals FALSE.
3305
     * empty() does not generate a warning if the variable does not exist.
3306
     *
3307
     * @param mixed $str
3308
     *
3309
     * @return bool whether or not $str is empty()
3310
     */
3311
    public static function is_empty($str): bool
3312
    {
3313
        return empty($str);
3314
    }
3315
3316
    /**
3317
     * Returns true if the string contains only hexadecimal chars, false otherwise.
3318
     *
3319
     * @param string $str
3320
     *
3321
     * @return bool
3322
     *              Whether or not $str contains only hexadecimal chars
3323
     */
3324 13
    public static function is_hexadecimal(string $str): bool
3325
    {
3326 13
        if (self::$SUPPORT['mbstring'] === true) {
3327
            /** @noinspection PhpComposerExtensionStubsInspection */
3328 13
            return \mb_ereg_match('^[[:xdigit:]]*$', $str);
3329
        }
3330
3331
        return self::str_matches_pattern($str, '^[[:xdigit:]]*$');
3332
    }
3333
3334
    /**
3335
     * Check if the string contains any HTML tags.
3336
     *
3337
     * @param string $str <p>The input string.</p>
3338
     *
3339
     * @return bool
3340
     */
3341 3
    public static function is_html(string $str): bool
3342
    {
3343 3
        if ($str === '') {
3344 3
            return false;
3345
        }
3346
3347
        // init
3348 3
        $matches = [];
3349
3350 3
        $str = self::emoji_encode($str); // hack for emoji support :/
3351
3352 3
        \preg_match("/<\\/?\\w+(?:(?:\\s+\\w+(?:\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)*\\s*|\\s*)\\/?>/u", $str, $matches);
3353
3354 3
        return \count($matches) !== 0;
3355
    }
3356
3357
    /**
3358
     * Try to check if "$str" is a JSON-string.
3359
     *
3360
     * @param string $str                                    <p>The input string.</p>
3361
     * @param bool   $only_array_or_object_results_are_valid [optional] <p>Only array and objects are valid json results.</p>
3362
     *
3363
     * @return bool
3364
     */
3365 42
    public static function is_json(
3366
        string $str,
3367
        $only_array_or_object_results_are_valid = true
3368
    ): bool {
3369 42
        if ($str === '') {
3370 4
            return false;
3371
        }
3372
3373 40
        if (self::$SUPPORT['json'] === false) {
3374
            throw new \RuntimeException('ext-json: is not installed');
3375
        }
3376
3377 40
        $json = self::json_decode($str);
3378 40
        if ($json === null && \strtoupper($str) !== 'NULL') {
3379 18
            return false;
3380
        }
3381
3382
        if (
3383 24
            $only_array_or_object_results_are_valid === true
3384
            &&
3385 24
            \is_object($json) === false
3386
            &&
3387 24
            \is_array($json) === false
3388
        ) {
3389 5
            return false;
3390
        }
3391
3392
        /** @noinspection PhpComposerExtensionStubsInspection */
3393 19
        return \json_last_error() === \JSON_ERROR_NONE;
3394
    }
3395
3396
    /**
3397
     * @param string $str
3398
     *
3399
     * @return bool
3400
     */
3401 8
    public static function is_lowercase(string $str): bool
3402
    {
3403 8
        if (self::$SUPPORT['mbstring'] === true) {
3404
            /** @noinspection PhpComposerExtensionStubsInspection */
3405 8
            return \mb_ereg_match('^[[:lower:]]*$', $str);
3406
        }
3407
3408
        return self::str_matches_pattern($str, '^[[:lower:]]*$');
3409
    }
3410
3411
    /**
3412
     * Returns true if the string is serialized, false otherwise.
3413
     *
3414
     * @param string $str
3415
     *
3416
     * @return bool whether or not $str is serialized
3417
     */
3418 7
    public static function is_serialized(string $str): bool
3419
    {
3420 7
        if ($str === '') {
3421 1
            return false;
3422
        }
3423
3424
        /** @noinspection PhpUsageOfSilenceOperatorInspection */
3425
        /** @noinspection UnserializeExploitsInspection */
3426 6
        return $str === 'b:0;'
3427
               ||
3428 6
               @\unserialize($str) !== false;
3429
    }
3430
3431
    /**
3432
     * Returns true if the string contains only lower case chars, false
3433
     * otherwise.
3434
     *
3435
     * @param string $str <p>The input string.</p>
3436
     *
3437
     * @return bool
3438
     *              <p>Whether or not $str contains only lower case characters.</p>
3439
     */
3440 8
    public static function is_uppercase(string $str): bool
3441
    {
3442 8
        if (self::$SUPPORT['mbstring'] === true) {
3443
            /** @noinspection PhpComposerExtensionStubsInspection */
3444 8
            return \mb_ereg_match('^[[:upper:]]*$', $str);
3445
        }
3446
3447
        return self::str_matches_pattern($str, '^[[:upper:]]*$');
3448
    }
3449
3450
    /**
3451
     * Check if the string is UTF-16.
3452
     *
3453
     * @param mixed $str                       <p>The input string.</p>
3454
     * @param bool  $check_if_string_is_binary
3455
     *
3456
     * @return false|int
3457
     *                   <strong>false</strong> if is't not UTF-16,<br>
3458
     *                   <strong>1</strong> for UTF-16LE,<br>
3459
     *                   <strong>2</strong> for UTF-16BE
3460
     */
3461 22
    public static function is_utf16($str, $check_if_string_is_binary = true)
3462
    {
3463
        // init
3464 22
        $str = (string) $str;
3465 22
        $str_chars = [];
3466
3467
        if (
3468 22
            $check_if_string_is_binary === true
3469
            &&
3470 22
            self::is_binary($str, true) === false
3471
        ) {
3472 2
            return false;
3473
        }
3474
3475 22
        if (self::$SUPPORT['mbstring'] === false) {
3476 3
            \trigger_error('UTF8::is_utf16() without mbstring may did not work correctly', \E_USER_WARNING);
3477
        }
3478
3479 22
        $str = self::remove_bom($str);
3480
3481 22
        $maybe_utf16le = 0;
3482 22
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-16LE');
3483 22
        if ($test) {
3484 15
            $test2 = \mb_convert_encoding($test, 'UTF-16LE', 'UTF-8');
3485 15
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-16LE');
3486 15
            if ($test3 === $test) {
3487 15
                if (\count($str_chars) === 0) {
3488 15
                    $str_chars = self::count_chars($str, true, false);
3489
                }
3490 15
                foreach (self::count_chars($test3) as $test3char => &$test3charEmpty) {
0 ignored issues
show
Bug introduced by
The expression self::count_chars($test3) cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
3491 15
                    if (\in_array($test3char, $str_chars, true) === true) {
3492 15
                        ++$maybe_utf16le;
3493
                    }
3494
                }
3495 15
                unset($test3charEmpty);
3496
            }
3497
        }
3498
3499 22
        $maybe_utf16be = 0;
3500 22
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-16BE');
3501 22
        if ($test) {
3502 15
            $test2 = \mb_convert_encoding($test, 'UTF-16BE', 'UTF-8');
3503 15
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-16BE');
3504 15
            if ($test3 === $test) {
3505 15
                if (\count($str_chars) === 0) {
3506 7
                    $str_chars = self::count_chars($str, true, false);
3507
                }
3508 15
                foreach (self::count_chars($test3) as $test3char => &$test3charEmpty) {
0 ignored issues
show
Bug introduced by
The expression self::count_chars($test3) cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
3509 15
                    if (\in_array($test3char, $str_chars, true) === true) {
3510 15
                        ++$maybe_utf16be;
3511
                    }
3512
                }
3513 15
                unset($test3charEmpty);
3514
            }
3515
        }
3516
3517 22
        if ($maybe_utf16be !== $maybe_utf16le) {
3518 7
            if ($maybe_utf16le > $maybe_utf16be) {
3519 5
                return 1;
3520
            }
3521
3522 6
            return 2;
3523
        }
3524
3525 18
        return false;
3526
    }
3527
3528
    /**
3529
     * Check if the string is UTF-32.
3530
     *
3531
     * @param mixed $str                       <p>The input string.</p>
3532
     * @param bool  $check_if_string_is_binary
3533
     *
3534
     * @return false|int
3535
     *                   <strong>false</strong> if is't not UTF-32,<br>
3536
     *                   <strong>1</strong> for UTF-32LE,<br>
3537
     *                   <strong>2</strong> for UTF-32BE
3538
     */
3539 20
    public static function is_utf32($str, $check_if_string_is_binary = true)
3540
    {
3541
        // init
3542 20
        $str = (string) $str;
3543 20
        $str_chars = [];
3544
3545
        if (
3546 20
            $check_if_string_is_binary === true
3547
            &&
3548 20
            self::is_binary($str, true) === false
3549
        ) {
3550 2
            return false;
3551
        }
3552
3553 20
        if (self::$SUPPORT['mbstring'] === false) {
3554 3
            \trigger_error('UTF8::is_utf32() without mbstring may did not work correctly', \E_USER_WARNING);
3555
        }
3556
3557 20
        $str = self::remove_bom($str);
3558
3559 20
        $maybe_utf32le = 0;
3560 20
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-32LE');
3561 20
        if ($test) {
3562 13
            $test2 = \mb_convert_encoding($test, 'UTF-32LE', 'UTF-8');
3563 13
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-32LE');
3564 13
            if ($test3 === $test) {
3565 13
                if (\count($str_chars) === 0) {
3566 13
                    $str_chars = self::count_chars($str, true, false);
3567
                }
3568 13
                foreach (self::count_chars($test3) as $test3char => &$test3charEmpty) {
0 ignored issues
show
Bug introduced by
The expression self::count_chars($test3) cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
3569 13
                    if (\in_array($test3char, $str_chars, true) === true) {
3570 13
                        ++$maybe_utf32le;
3571
                    }
3572
                }
3573 13
                unset($test3charEmpty);
3574
            }
3575
        }
3576
3577 20
        $maybe_utf32be = 0;
3578 20
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-32BE');
3579 20
        if ($test) {
3580 13
            $test2 = \mb_convert_encoding($test, 'UTF-32BE', 'UTF-8');
3581 13
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-32BE');
3582 13
            if ($test3 === $test) {
3583 13
                if (\count($str_chars) === 0) {
3584 7
                    $str_chars = self::count_chars($str, true, false);
3585
                }
3586 13
                foreach (self::count_chars($test3) as $test3char => &$test3charEmpty) {
0 ignored issues
show
Bug introduced by
The expression self::count_chars($test3) cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
3587 13
                    if (\in_array($test3char, $str_chars, true) === true) {
3588 13
                        ++$maybe_utf32be;
3589
                    }
3590
                }
3591 13
                unset($test3charEmpty);
3592
            }
3593
        }
3594
3595 20
        if ($maybe_utf32be !== $maybe_utf32le) {
3596 3
            if ($maybe_utf32le > $maybe_utf32be) {
3597 2
                return 1;
3598
            }
3599
3600 3
            return 2;
3601
        }
3602
3603 20
        return false;
3604
    }
3605
3606
    /**
3607
     * Checks whether the passed input contains only byte sequences that appear valid UTF-8.
3608
     *
3609
     * @param int|string|string[]|null $str    <p>The input to be checked.</p>
3610
     * @param bool                     $strict <p>Check also if the string is not UTF-16 or UTF-32.</p>
3611
     *
3612
     * @return bool
3613
     */
3614 82
    public static function is_utf8($str, bool $strict = false): bool
3615
    {
3616 82
        if (\is_array($str) === true) {
3617 2
            foreach ($str as &$v) {
3618 2
                if (self::is_utf8($v, $strict) === false) {
3619 2
                    return false;
3620
                }
3621
            }
3622
3623
            return true;
3624
        }
3625
3626 82
        return self::is_utf8_string((string) $str, $strict);
3627
    }
3628
3629
    /**
3630
     * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
3631
     * Decodes a JSON string
3632
     *
3633
     * @see http://php.net/manual/en/function.json-decode.php
3634
     *
3635
     * @param string $json    <p>
3636
     *                        The <i>json</i> string being decoded.
3637
     *                        </p>
3638
     *                        <p>
3639
     *                        This function only works with UTF-8 encoded strings.
3640
     *                        </p>
3641
     *                        <p>PHP implements a superset of
3642
     *                        JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
3643
     *                        only supports these values when they are nested inside an array or an object.
3644
     *                        </p>
3645
     * @param bool   $assoc   [optional] <p>
3646
     *                        When <b>TRUE</b>, returned objects will be converted into
3647
     *                        associative arrays.
3648
     *                        </p>
3649
     * @param int    $depth   [optional] <p>
3650
     *                        User specified recursion depth.
3651
     *                        </p>
3652
     * @param int    $options [optional] <p>
3653
     *                        Bitmask of JSON decode options. Currently only
3654
     *                        <b>JSON_BIGINT_AS_STRING</b>
3655
     *                        is supported (default is to cast large integers as floats)
3656
     *                        </p>
3657
     *
3658
     * @return mixed
3659
     *               The value encoded in <i>json</i> in appropriate PHP type. Values true, false and
3660
     *               null (case-insensitive) are returned as <b>TRUE</b>, <b>FALSE</b> and <b>NULL</b> respectively.
3661
     *               <b>NULL</b> is returned if the <i>json</i> cannot be decoded or if the encoded data
3662
     *               is deeper than the recursion limit.
3663
     */
3664 43
    public static function json_decode(
3665
        string $json,
3666
        bool $assoc = false,
3667
        int $depth = 512,
3668
        int $options = 0
3669
    ) {
3670 43
        $json = self::filter($json);
3671
3672 43
        if (self::$SUPPORT['json'] === false) {
3673
            throw new \RuntimeException('ext-json: is not installed');
3674
        }
3675
3676
        /** @noinspection PhpComposerExtensionStubsInspection */
3677 43
        return \json_decode($json, $assoc, $depth, $options);
3678
    }
3679
3680
    /**
3681
     * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
3682
     * Returns the JSON representation of a value.
3683
     *
3684
     * @see http://php.net/manual/en/function.json-encode.php
3685
     *
3686
     * @param mixed $value   <p>
3687
     *                       The <i>value</i> being encoded. Can be any type except
3688
     *                       a resource.
3689
     *                       </p>
3690
     *                       <p>
3691
     *                       All string data must be UTF-8 encoded.
3692
     *                       </p>
3693
     *                       <p>PHP implements a superset of
3694
     *                       JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
3695
     *                       only supports these values when they are nested inside an array or an object.
3696
     *                       </p>
3697
     * @param int   $options [optional] <p>
3698
     *                       Bitmask consisting of <b>JSON_HEX_QUOT</b>,
3699
     *                       <b>JSON_HEX_TAG</b>,
3700
     *                       <b>JSON_HEX_AMP</b>,
3701
     *                       <b>JSON_HEX_APOS</b>,
3702
     *                       <b>JSON_NUMERIC_CHECK</b>,
3703
     *                       <b>JSON_PRETTY_PRINT</b>,
3704
     *                       <b>JSON_UNESCAPED_SLASHES</b>,
3705
     *                       <b>JSON_FORCE_OBJECT</b>,
3706
     *                       <b>JSON_UNESCAPED_UNICODE</b>. The behaviour of these
3707
     *                       constants is described on
3708
     *                       the JSON constants page.
3709
     *                       </p>
3710
     * @param int   $depth   [optional] <p>
3711
     *                       Set the maximum depth. Must be greater than zero.
3712
     *                       </p>
3713
     *
3714
     * @return false|string
3715
     *                      A JSON encoded <strong>string</strong> on success or<br>
3716
     *                      <strong>FALSE</strong> on failure
3717
     */
3718 5
    public static function json_encode($value, int $options = 0, int $depth = 512)
3719
    {
3720 5
        $value = self::filter($value);
3721
3722 5
        if (self::$SUPPORT['json'] === false) {
3723
            throw new \RuntimeException('ext-json: is not installed');
3724
        }
3725
3726
        /** @noinspection PhpComposerExtensionStubsInspection */
3727 5
        return \json_encode($value, $options, $depth);
3728
    }
3729
3730
    /**
3731
     * Checks whether JSON is available on the server.
3732
     *
3733
     * @return bool
3734
     *              <strong>true</strong> if available, <strong>false</strong> otherwise
3735
     */
3736
    public static function json_loaded(): bool
3737
    {
3738
        return \function_exists('json_decode');
3739
    }
3740
3741
    /**
3742
     * Makes string's first char lowercase.
3743
     *
3744
     * @param string      $str                           <p>The input string</p>
3745
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
3746
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
3747
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt, tr</p>
3748
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
3749
     *
3750
     * @return string the resulting string
3751
     */
3752 46
    public static function lcfirst(
3753
        string $str,
3754
        string $encoding = 'UTF-8',
3755
        bool $clean_utf8 = false,
3756
        string $lang = null,
3757
        bool $try_to_keep_the_string_length = false
3758
    ): string {
3759 46
        if ($clean_utf8 === true) {
3760
            $str = self::clean($str);
3761
        }
3762
3763 46
        $use_mb_functions = ($lang === null && $try_to_keep_the_string_length === false);
3764
3765 46
        if ($encoding === 'UTF-8') {
3766 43
            $str_part_two = (string) \mb_substr($str, 1);
3767
3768 43
            if ($use_mb_functions === true) {
3769 43
                $str_part_one = \mb_strtolower(
3770 43
                    (string) \mb_substr($str, 0, 1)
3771
                );
3772
            } else {
3773
                $str_part_one = self::strtolower(
3774
                    (string) \mb_substr($str, 0, 1),
3775
                    $encoding,
3776
                    false,
3777
                    $lang,
3778 43
                    $try_to_keep_the_string_length
3779
                );
3780
            }
3781
        } else {
3782 3
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
3783
3784 3
            $str_part_two = (string) self::substr($str, 1, null, $encoding);
3785
3786 3
            $str_part_one = self::strtolower(
3787 3
                (string) self::substr($str, 0, 1, $encoding),
3788 3
                $encoding,
3789 3
                false,
3790 3
                $lang,
3791 3
                $try_to_keep_the_string_length
3792
            );
3793
        }
3794
3795 46
        return $str_part_one . $str_part_two;
3796
    }
3797
3798
    /**
3799
     * alias for "UTF8::lcfirst()"
3800
     *
3801
     * @param string      $str
3802
     * @param string      $encoding
3803
     * @param bool        $clean_utf8
3804
     * @param string|null $lang
3805
     * @param bool        $try_to_keep_the_string_length
3806
     *
3807
     * @return string
3808
     *
3809
     * @see UTF8::lcfirst()
3810
     * @deprecated <p>please use "UTF8::lcfirst()"</p>
3811
     */
3812 2
    public static function lcword(
3813
        string $str,
3814
        string $encoding = 'UTF-8',
3815
        bool $clean_utf8 = false,
3816
        string $lang = null,
3817
        bool $try_to_keep_the_string_length = false
3818
    ): string {
3819 2
        return self::lcfirst(
3820 2
            $str,
3821 2
            $encoding,
3822 2
            $clean_utf8,
3823 2
            $lang,
3824 2
            $try_to_keep_the_string_length
3825
        );
3826
    }
3827
3828
    /**
3829
     * Lowercase for all words in the string.
3830
     *
3831
     * @param string      $str                           <p>The input string.</p>
3832
     * @param string[]    $exceptions                    [optional] <p>Exclusion for some words.</p>
3833
     * @param string      $char_list                     [optional] <p>Additional chars that contains to words and do not start
3834
     *                                                   a new word.</p>
3835
     * @param string      $encoding                      [optional] <p>Set the charset.</p>
3836
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
3837
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt, tr</p>
3838
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
3839
     *
3840
     * @return string
3841
     */
3842 2
    public static function lcwords(
3843
        string $str,
3844
        array $exceptions = [],
3845
        string $char_list = '',
3846
        string $encoding = 'UTF-8',
3847
        bool $clean_utf8 = false,
3848
        string $lang = null,
3849
        bool $try_to_keep_the_string_length = false
3850
    ): string {
3851 2
        if (!$str) {
3852 2
            return '';
3853
        }
3854
3855 2
        $words = self::str_to_words($str, $char_list);
3856 2
        $use_exceptions = \count($exceptions) > 0;
3857
3858 2
        foreach ($words as &$word) {
3859 2
            if (!$word) {
3860 2
                continue;
3861
            }
3862
3863
            if (
3864 2
                $use_exceptions === false
3865
                ||
3866 2
                !\in_array($word, $exceptions, true)
3867
            ) {
3868 2
                $word = self::lcfirst($word, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
3869
            }
3870
        }
3871
3872 2
        return \implode('', $words);
3873
    }
3874
3875
    /**
3876
     * alias for "UTF8::lcfirst()"
3877
     *
3878
     * @param string      $str
3879
     * @param string      $encoding
3880
     * @param bool        $clean_utf8
3881
     * @param string|null $lang
3882
     * @param bool        $try_to_keep_the_string_length
3883
     *
3884
     * @return string
3885
     *
3886
     * @see UTF8::lcfirst()
3887
     * @deprecated <p>please use "UTF8::lcfirst()"</p>
3888
     */
3889 5
    public static function lowerCaseFirst(
3890
        string $str,
3891
        string $encoding = 'UTF-8',
3892
        bool $clean_utf8 = false,
3893
        string $lang = null,
3894
        bool $try_to_keep_the_string_length = false
3895
    ): string {
3896 5
        return self::lcfirst(
3897 5
            $str,
3898 5
            $encoding,
3899 5
            $clean_utf8,
3900 5
            $lang,
3901 5
            $try_to_keep_the_string_length
3902
        );
3903
    }
3904
3905
    /**
3906
     * Strip whitespace or other characters from the beginning of a UTF-8 string.
3907
     *
3908
     * @param string      $str   <p>The string to be trimmed</p>
3909
     * @param string|null $chars <p>Optional characters to be stripped</p>
3910
     *
3911
     * @return string the string with unwanted characters stripped from the left
3912
     */
3913 22
    public static function ltrim(string $str = '', string $chars = null): string
3914
    {
3915 22
        if ($str === '') {
3916 3
            return '';
3917
        }
3918
3919 21
        if ($chars) {
3920 10
            $chars = \preg_quote($chars, '/');
3921 10
            $pattern = "^[${chars}]+";
3922
        } else {
3923 14
            $pattern = '^[\\s]+';
3924
        }
3925
3926 21
        if (self::$SUPPORT['mbstring'] === true) {
3927
            /** @noinspection PhpComposerExtensionStubsInspection */
3928 21
            return (string) \mb_ereg_replace($pattern, '', $str);
3929
        }
3930
3931
        return self::regex_replace($str, $pattern, '', '', '/');
3932
    }
3933
3934
    /**
3935
     * Returns the UTF-8 character with the maximum code point in the given data.
3936
     *
3937
     * @param array<string>|string $arg <p>A UTF-8 encoded string or an array of such strings.</p>
3938
     *
3939
     * @return string|null the character with the highest code point than others, returns null on failure or empty input
3940
     */
3941 2
    public static function max($arg)
3942
    {
3943 2
        if (\is_array($arg) === true) {
3944 2
            $arg = \implode('', $arg);
3945
        }
3946
3947 2
        $codepoints = self::codepoints($arg, false);
3948 2
        if (\count($codepoints) === 0) {
3949 2
            return null;
3950
        }
3951
3952 2
        $codepoint_max = \max($codepoints);
3953
3954 2
        return self::chr($codepoint_max);
3955
    }
3956
3957
    /**
3958
     * Calculates and returns the maximum number of bytes taken by any
3959
     * UTF-8 encoded character in the given string.
3960
     *
3961
     * @param string $str <p>The original Unicode string.</p>
3962
     *
3963
     * @return int max byte lengths of the given chars
3964
     */
3965 2
    public static function max_chr_width(string $str): int
3966
    {
3967 2
        $bytes = self::chr_size_list($str);
3968 2
        if (\count($bytes) > 0) {
3969 2
            return (int) \max($bytes);
3970
        }
3971
3972 2
        return 0;
3973
    }
3974
3975
    /**
3976
     * Checks whether mbstring is available on the server.
3977
     *
3978
     * @return bool
3979
     *              <strong>true</strong> if available, <strong>false</strong> otherwise
3980
     */
3981 28
    public static function mbstring_loaded(): bool
3982
    {
3983 28
        return \extension_loaded('mbstring');
3984
    }
3985
3986
    /**
3987
     * Returns the UTF-8 character with the minimum code point in the given data.
3988
     *
3989
     * @param mixed $arg <strong>A UTF-8 encoded string or an array of such strings.</strong>
3990
     *
3991
     * @return string|null the character with the lowest code point than others, returns null on failure or empty input
3992
     */
3993 2
    public static function min($arg)
3994
    {
3995 2
        if (\is_array($arg) === true) {
3996 2
            $arg = \implode('', $arg);
3997
        }
3998
3999 2
        $codepoints = self::codepoints($arg, false);
4000 2
        if (\count($codepoints) === 0) {
4001 2
            return null;
4002
        }
4003
4004 2
        $codepoint_min = \min($codepoints);
4005
4006 2
        return self::chr($codepoint_min);
4007
    }
4008
4009
    /**
4010
     * alias for "UTF8::normalize_encoding()"
4011
     *
4012
     * @param mixed $encoding
4013
     * @param mixed $fallback
4014
     *
4015
     * @return mixed
4016
     *
4017
     * @see UTF8::normalize_encoding()
4018
     * @deprecated <p>please use "UTF8::normalize_encoding()"</p>
4019
     */
4020 2
    public static function normalizeEncoding($encoding, $fallback = '')
4021
    {
4022 2
        return self::normalize_encoding($encoding, $fallback);
4023
    }
4024
4025
    /**
4026
     * Normalize the encoding-"name" input.
4027
     *
4028
     * @param mixed $encoding <p>e.g.: ISO, UTF8, WINDOWS-1251 etc.</p>
4029
     * @param mixed $fallback <p>e.g.: UTF-8</p>
4030
     *
4031
     * @return mixed e.g.: ISO-8859-1, UTF-8, WINDOWS-1251 etc.<br>Will return a empty string as fallback (by default)
4032
     */
4033 331
    public static function normalize_encoding($encoding, $fallback = '')
4034
    {
4035 331
        static $STATIC_NORMALIZE_ENCODING_CACHE = [];
4036
4037
        // init
4038 331
        $encoding = (string) $encoding;
4039
4040 331
        if (!$encoding) {
4041 285
            return $fallback;
4042
        }
4043
4044
        if (
4045 51
            $encoding === 'UTF-8'
4046
            ||
4047 51
            $encoding === 'UTF8'
4048
        ) {
4049 26
            return 'UTF-8';
4050
        }
4051
4052
        if (
4053 43
            $encoding === '8BIT'
4054
            ||
4055 43
            $encoding === 'BINARY'
4056
        ) {
4057
            return 'CP850';
4058
        }
4059
4060
        if (
4061 43
            $encoding === 'HTML'
4062
            ||
4063 43
            $encoding === 'HTML-ENTITIES'
4064
        ) {
4065 2
            return 'HTML-ENTITIES';
4066
        }
4067
4068
        if (
4069 43
            $encoding === '1' // only a fallback, for non "strict_types" usage ...
4070
            ||
4071 43
            $encoding === '0' // only a fallback, for non "strict_types" usage ...
4072
        ) {
4073 1
            return $fallback;
4074
        }
4075
4076 42
        if (isset($STATIC_NORMALIZE_ENCODING_CACHE[$encoding])) {
4077 40
            return $STATIC_NORMALIZE_ENCODING_CACHE[$encoding];
4078
        }
4079
4080 6
        if (self::$ENCODINGS === null) {
4081 1
            self::$ENCODINGS = self::getData('encodings');
4082
        }
4083
4084 6
        if (\in_array($encoding, self::$ENCODINGS, true)) {
4085 4
            $STATIC_NORMALIZE_ENCODING_CACHE[$encoding] = $encoding;
4086
4087 4
            return $encoding;
4088
        }
4089
4090 5
        $encoding_original = $encoding;
4091 5
        $encoding = \strtoupper($encoding);
4092 5
        $encoding_upper_helper = (string) \preg_replace('/[^a-zA-Z0-9]/u', '', $encoding);
4093
4094
        $equivalences = [
4095 5
            'ISO8859'     => 'ISO-8859-1',
4096
            'ISO88591'    => 'ISO-8859-1',
4097
            'ISO'         => 'ISO-8859-1',
4098
            'LATIN'       => 'ISO-8859-1',
4099
            'LATIN1'      => 'ISO-8859-1', // Western European
4100
            'ISO88592'    => 'ISO-8859-2',
4101
            'LATIN2'      => 'ISO-8859-2', // Central European
4102
            'ISO88593'    => 'ISO-8859-3',
4103
            'LATIN3'      => 'ISO-8859-3', // Southern European
4104
            'ISO88594'    => 'ISO-8859-4',
4105
            'LATIN4'      => 'ISO-8859-4', // Northern European
4106
            'ISO88595'    => 'ISO-8859-5',
4107
            'ISO88596'    => 'ISO-8859-6', // Greek
4108
            'ISO88597'    => 'ISO-8859-7',
4109
            'ISO88598'    => 'ISO-8859-8', // Hebrew
4110
            'ISO88599'    => 'ISO-8859-9',
4111
            'LATIN5'      => 'ISO-8859-9', // Turkish
4112
            'ISO885911'   => 'ISO-8859-11',
4113
            'TIS620'      => 'ISO-8859-11', // Thai
4114
            'ISO885910'   => 'ISO-8859-10',
4115
            'LATIN6'      => 'ISO-8859-10', // Nordic
4116
            'ISO885913'   => 'ISO-8859-13',
4117
            'LATIN7'      => 'ISO-8859-13', // Baltic
4118
            'ISO885914'   => 'ISO-8859-14',
4119
            'LATIN8'      => 'ISO-8859-14', // Celtic
4120
            'ISO885915'   => 'ISO-8859-15',
4121
            'LATIN9'      => 'ISO-8859-15', // Western European (with some extra chars e.g. €)
4122
            'ISO885916'   => 'ISO-8859-16',
4123
            'LATIN10'     => 'ISO-8859-16', // Southeast European
4124
            'CP1250'      => 'WINDOWS-1250',
4125
            'WIN1250'     => 'WINDOWS-1250',
4126
            'WINDOWS1250' => 'WINDOWS-1250',
4127
            'CP1251'      => 'WINDOWS-1251',
4128
            'WIN1251'     => 'WINDOWS-1251',
4129
            'WINDOWS1251' => 'WINDOWS-1251',
4130
            'CP1252'      => 'WINDOWS-1252',
4131
            'WIN1252'     => 'WINDOWS-1252',
4132
            'WINDOWS1252' => 'WINDOWS-1252',
4133
            'CP1253'      => 'WINDOWS-1253',
4134
            'WIN1253'     => 'WINDOWS-1253',
4135
            'WINDOWS1253' => 'WINDOWS-1253',
4136
            'CP1254'      => 'WINDOWS-1254',
4137
            'WIN1254'     => 'WINDOWS-1254',
4138
            'WINDOWS1254' => 'WINDOWS-1254',
4139
            'CP1255'      => 'WINDOWS-1255',
4140
            'WIN1255'     => 'WINDOWS-1255',
4141
            'WINDOWS1255' => 'WINDOWS-1255',
4142
            'CP1256'      => 'WINDOWS-1256',
4143
            'WIN1256'     => 'WINDOWS-1256',
4144
            'WINDOWS1256' => 'WINDOWS-1256',
4145
            'CP1257'      => 'WINDOWS-1257',
4146
            'WIN1257'     => 'WINDOWS-1257',
4147
            'WINDOWS1257' => 'WINDOWS-1257',
4148
            'CP1258'      => 'WINDOWS-1258',
4149
            'WIN1258'     => 'WINDOWS-1258',
4150
            'WINDOWS1258' => 'WINDOWS-1258',
4151
            'UTF16'       => 'UTF-16',
4152
            'UTF32'       => 'UTF-32',
4153
            'UTF8'        => 'UTF-8',
4154
            'UTF'         => 'UTF-8',
4155
            'UTF7'        => 'UTF-7',
4156
            '8BIT'        => 'CP850',
4157
            'BINARY'      => 'CP850',
4158
        ];
4159
4160 5
        if (!empty($equivalences[$encoding_upper_helper])) {
4161 4
            $encoding = $equivalences[$encoding_upper_helper];
4162
        }
4163
4164 5
        $STATIC_NORMALIZE_ENCODING_CACHE[$encoding_original] = $encoding;
4165
4166 5
        return $encoding;
4167
    }
4168
4169
    /**
4170
     * Standardize line ending to unix-like.
4171
     *
4172
     * @param string $str
4173
     *
4174
     * @return string
4175
     */
4176 5
    public static function normalize_line_ending(string $str): string
4177
    {
4178 5
        return \str_replace(["\r\n", "\r"], "\n", $str);
4179
    }
4180
4181
    /**
4182
     * Normalize some MS Word special characters.
4183
     *
4184
     * @param string $str <p>The string to be normalized.</p>
4185
     *
4186
     * @return string
4187
     */
4188 10
    public static function normalize_msword(string $str): string
4189
    {
4190 10
        return ASCII::normalize_msword($str);
4191
    }
4192
4193
    /**
4194
     * Normalize the whitespace.
4195
     *
4196
     * @param string $str                        <p>The string to be normalized.</p>
4197
     * @param bool   $keep_non_breaking_space    [optional] <p>Set to true, to keep non-breaking-spaces.</p>
4198
     * @param bool   $keep_bidi_unicode_controls [optional] <p>Set to true, to keep non-printable (for the web)
4199
     *                                           bidirectional text chars.</p>
4200
     *
4201
     * @return string
4202
     */
4203 61
    public static function normalize_whitespace(
4204
        string $str,
4205
        bool $keep_non_breaking_space = false,
4206
        bool $keep_bidi_unicode_controls = false
4207
    ): string {
4208 61
        return ASCII::normalize_whitespace(
4209 61
            $str,
4210 61
            $keep_non_breaking_space,
4211 61
            $keep_bidi_unicode_controls
4212
        );
4213
    }
4214
4215
    /**
4216
     * Calculates Unicode code point of the given UTF-8 encoded character.
4217
     *
4218
     * INFO: opposite to UTF8::chr()
4219
     *
4220
     * @param string $chr      <p>The character of which to calculate code point.<p/>
4221
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
4222
     *
4223
     * @return int
4224
     *             Unicode code point of the given character,<br>
4225
     *             0 on invalid UTF-8 byte sequence
4226
     */
4227 30
    public static function ord($chr, string $encoding = 'UTF-8'): int
4228
    {
4229 30
        static $CHAR_CACHE = [];
4230
4231
        // init
4232 30
        $chr = (string) $chr;
4233
4234 30
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
4235 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
4236
        }
4237
4238 30
        $cache_key = $chr . $encoding;
4239 30
        if (isset($CHAR_CACHE[$cache_key]) === true) {
4240 30
            return $CHAR_CACHE[$cache_key];
4241
        }
4242
4243
        // check again, if it's still not UTF-8
4244 12
        if ($encoding !== 'UTF-8') {
4245 3
            $chr = self::encode($encoding, $chr);
4246
        }
4247
4248 12
        if (self::$ORD === null) {
4249
            self::$ORD = self::getData('ord');
4250
        }
4251
4252 12
        if (isset(self::$ORD[$chr])) {
4253 12
            return $CHAR_CACHE[$cache_key] = self::$ORD[$chr];
4254
        }
4255
4256
        //
4257
        // fallback via "IntlChar"
4258
        //
4259
4260 6
        if (self::$SUPPORT['intlChar'] === true) {
4261
            /** @noinspection PhpComposerExtensionStubsInspection */
4262 5
            $code = \IntlChar::ord($chr);
4263 5
            if ($code) {
4264 5
                return $CHAR_CACHE[$cache_key] = $code;
4265
            }
4266
        }
4267
4268
        //
4269
        // fallback via vanilla php
4270
        //
4271
4272
        /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
4273 1
        $chr = \unpack('C*', (string) \substr($chr, 0, 4));
4274
        /** @noinspection OffsetOperationsInspection */
4275 1
        $code = $chr ? $chr[1] : 0;
4276
4277
        /** @noinspection OffsetOperationsInspection */
4278 1
        if ($code >= 0xF0 && isset($chr[4])) {
4279
            /** @noinspection UnnecessaryCastingInspection */
4280
            /** @noinspection OffsetOperationsInspection */
4281
            return $CHAR_CACHE[$cache_key] = (int) ((($code - 0xF0) << 18) + (($chr[2] - 0x80) << 12) + (($chr[3] - 0x80) << 6) + $chr[4] - 0x80);
4282
        }
4283
4284
        /** @noinspection OffsetOperationsInspection */
4285 1
        if ($code >= 0xE0 && isset($chr[3])) {
4286
            /** @noinspection UnnecessaryCastingInspection */
4287
            /** @noinspection OffsetOperationsInspection */
4288 1
            return $CHAR_CACHE[$cache_key] = (int) ((($code - 0xE0) << 12) + (($chr[2] - 0x80) << 6) + $chr[3] - 0x80);
4289
        }
4290
4291
        /** @noinspection OffsetOperationsInspection */
4292 1
        if ($code >= 0xC0 && isset($chr[2])) {
4293
            /** @noinspection UnnecessaryCastingInspection */
4294
            /** @noinspection OffsetOperationsInspection */
4295 1
            return $CHAR_CACHE[$cache_key] = (int) ((($code - 0xC0) << 6) + $chr[2] - 0x80);
4296
        }
4297
4298
        return $CHAR_CACHE[$cache_key] = $code;
4299
    }
4300
4301
    /**
4302
     * Parses the string into an array (into the the second parameter).
4303
     *
4304
     * WARNING: Unlike "parse_str()", this method does not (re-)place variables in the current scope,
4305
     *          if the second parameter is not set!
4306
     *
4307
     * @see http://php.net/manual/en/function.parse-str.php
4308
     *
4309
     * @param string $str        <p>The input string.</p>
4310
     * @param array  $result     <p>The result will be returned into this reference parameter.</p>
4311
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
4312
     *
4313
     * @return bool
4314
     *              Will return <strong>false</strong> if php can't parse the string and we haven't any $result
4315
     */
4316 2
    public static function parse_str(string $str, &$result, bool $clean_utf8 = false): bool
4317
    {
4318 2
        if ($clean_utf8 === true) {
4319 2
            $str = self::clean($str);
4320
        }
4321
4322 2
        if (self::$SUPPORT['mbstring'] === true) {
4323 2
            $return = \mb_parse_str($str, $result);
4324
4325 2
            return $return !== false && $result !== [];
4326
        }
4327
4328
        /** @noinspection PhpVoidFunctionResultUsedInspection */
4329
        \parse_str($str, $result);
4330
4331
        return $result !== [];
4332
    }
4333
4334
    /**
4335
     * Checks if \u modifier is available that enables Unicode support in PCRE.
4336
     *
4337
     * @return bool
4338
     *              <strong>true</strong> if support is available,<br>
4339
     *              <strong>false</strong> otherwise
4340
     */
4341 102
    public static function pcre_utf8_support(): bool
4342
    {
4343
        /** @noinspection PhpUsageOfSilenceOperatorInspection */
4344 102
        return (bool) @\preg_match('//u', '');
4345
    }
4346
4347
    /**
4348
     * Create an array containing a range of UTF-8 characters.
4349
     *
4350
     * @param mixed     $var1      <p>Numeric or hexadecimal code points, or a UTF-8 character to start from.</p>
4351
     * @param mixed     $var2      <p>Numeric or hexadecimal code points, or a UTF-8 character to end at.</p>
4352
     * @param bool      $use_ctype <p>use ctype to detect numeric and hexadecimal, otherwise we will use a simple "is_numeric"</p>
4353
     * @param string    $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
4354
     * @param float|int $step      [optional] <p>
4355
     *                             If a step value is given, it will be used as the
4356
     *                             increment between elements in the sequence. step
4357
     *                             should be given as a positive number. If not specified,
4358
     *                             step will default to 1.
4359
     *                             </p>
4360
     *
4361
     * @return string[]
4362
     */
4363 2
    public static function range(
4364
        $var1,
4365
        $var2,
4366
        bool $use_ctype = true,
4367
        string $encoding = 'UTF-8',
4368
        $step = 1
4369
    ): array {
4370 2
        if (!$var1 || !$var2) {
4371 2
            return [];
4372
        }
4373
4374 2
        if ($step !== 1) {
4375 1
            if (!\is_numeric($step)) {
0 ignored issues
show
introduced by
The condition is_numeric($step) is always true.
Loading history...
4376
                throw new \InvalidArgumentException('$step need to be a number, type given: ' . \gettype($step));
4377
            }
4378
4379 1
            if ($step <= 0) {
4380
                throw new \InvalidArgumentException('$step need to be a positive number, given: ' . $step);
4381
            }
4382
        }
4383
4384 2
        if ($use_ctype && self::$SUPPORT['ctype'] === false) {
4385
            throw new \RuntimeException('ext-ctype: is not installed');
4386
        }
4387
4388 2
        $is_digit = false;
4389 2
        $is_xdigit = false;
4390
4391
        /** @noinspection PhpComposerExtensionStubsInspection */
4392 2
        if ($use_ctype && \ctype_digit((string) $var1) && \ctype_digit((string) $var2)) {
4393 2
            $is_digit = true;
4394 2
            $start = (int) $var1;
4395 2
        } /** @noinspection PhpComposerExtensionStubsInspection */ elseif ($use_ctype && \ctype_xdigit($var1) && \ctype_xdigit($var2)) {
4396
            $is_xdigit = true;
4397
            $start = (int) self::hex_to_int($var1);
4398 2
        } elseif (!$use_ctype && \is_numeric($var1)) {
4399 1
            $start = (int) $var1;
4400
        } else {
4401 2
            $start = self::ord($var1);
4402
        }
4403
4404 2
        if (!$start) {
4405
            return [];
4406
        }
4407
4408 2
        if ($is_digit) {
4409 2
            $end = (int) $var2;
4410 2
        } elseif ($is_xdigit) {
4411
            $end = (int) self::hex_to_int($var2);
4412 2
        } elseif (!$use_ctype && \is_numeric($var2)) {
4413 1
            $end = (int) $var2;
4414
        } else {
4415 2
            $end = self::ord($var2);
4416
        }
4417
4418 2
        if (!$end) {
4419
            return [];
4420
        }
4421
4422 2
        $array = [];
4423 2
        foreach (\range($start, $end, $step) as $i) {
4424 2
            $array[] = (string) self::chr((int) $i, $encoding);
4425
        }
4426
4427 2
        return $array;
4428
    }
4429
4430
    /**
4431
     * Multi decode HTML entity + fix urlencoded-win1252-chars.
4432
     *
4433
     * e.g:
4434
     * 'test+test'                     => 'test+test'
4435
     * 'D&#252;sseldorf'               => 'Düsseldorf'
4436
     * 'D%FCsseldorf'                  => 'Düsseldorf'
4437
     * 'D&#xFC;sseldorf'               => 'Düsseldorf'
4438
     * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
4439
     * 'Düsseldorf'                   => 'Düsseldorf'
4440
     * 'D%C3%BCsseldorf'               => 'Düsseldorf'
4441
     * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
4442
     * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
4443
     *
4444
     * @param string $str          <p>The input string.</p>
4445
     * @param bool   $multi_decode <p>Decode as often as possible.</p>
4446
     *
4447
     * @return string
4448
     */
4449 6
    public static function rawurldecode(string $str, bool $multi_decode = true): string
4450
    {
4451 6
        if ($str === '') {
4452 4
            return '';
4453
        }
4454
4455
        if (
4456 6
            \strpos($str, '&') === false
4457
            &&
4458 6
            \strpos($str, '%') === false
4459
            &&
4460 6
            \strpos($str, '+') === false
4461
            &&
4462 6
            \strpos($str, '\u') === false
4463
        ) {
4464 4
            return self::fix_simple_utf8($str);
4465
        }
4466
4467 6
        $str = self::urldecode_unicode_helper($str);
4468
4469
        do {
4470 6
            $str_compare = $str;
4471
4472
            /**
4473
             * @psalm-suppress PossiblyInvalidArgument
4474
             */
4475 6
            $str = self::fix_simple_utf8(
4476 6
                \rawurldecode(
4477 6
                    self::html_entity_decode(
4478 6
                        self::to_utf8($str),
4479 6
                        \ENT_QUOTES | \ENT_HTML5
4480
                    )
4481
                )
4482
            );
4483 6
        } while ($multi_decode === true && $str_compare !== $str);
4484
4485 6
        return $str;
4486
    }
4487
4488
    /**
4489
     * Replaces all occurrences of $pattern in $str by $replacement.
4490
     *
4491
     * @param string $str         <p>The input string.</p>
4492
     * @param string $pattern     <p>The regular expression pattern.</p>
4493
     * @param string $replacement <p>The string to replace with.</p>
4494
     * @param string $options     [optional] <p>Matching conditions to be used.</p>
4495
     * @param string $delimiter   [optional] <p>Delimiter the the regex. Default: '/'</p>
4496
     *
4497
     * @return string
4498
     */
4499 18
    public static function regex_replace(
4500
        string $str,
4501
        string $pattern,
4502
        string $replacement,
4503
        string $options = '',
4504
        string $delimiter = '/'
4505
    ): string {
4506 18
        if ($options === 'msr') {
4507 9
            $options = 'ms';
4508
        }
4509
4510
        // fallback
4511 18
        if (!$delimiter) {
4512
            $delimiter = '/';
4513
        }
4514
4515 18
        return (string) \preg_replace(
4516 18
            $delimiter . $pattern . $delimiter . 'u' . $options,
4517 18
            $replacement,
4518 18
            $str
4519
        );
4520
    }
4521
4522
    /**
4523
     * alias for "UTF8::remove_bom()"
4524
     *
4525
     * @param string $str
4526
     *
4527
     * @return string
4528
     *
4529
     * @see UTF8::remove_bom()
4530
     * @deprecated <p>please use "UTF8::remove_bom()"</p>
4531
     */
4532
    public static function removeBOM(string $str): string
4533
    {
4534
        return self::remove_bom($str);
4535
    }
4536
4537
    /**
4538
     * Remove the BOM from UTF-8 / UTF-16 / UTF-32 strings.
4539
     *
4540
     * @param string $str <p>The input string.</p>
4541
     *
4542
     * @return string string without UTF-BOM
4543
     */
4544 55
    public static function remove_bom(string $str): string
4545
    {
4546 55
        if ($str === '') {
4547 9
            return '';
4548
        }
4549
4550 55
        $str_length = \strlen($str);
4551 55
        foreach (self::$BOM as $bom_string => $bom_byte_length) {
4552 55
            if (\strpos($str, $bom_string, 0) === 0) {
4553
                /** @var string|false $str_tmp - needed for PhpStan (stubs error) */
4554 11
                $str_tmp = \substr($str, $bom_byte_length, $str_length);
4555 11
                if ($str_tmp === false) {
4556
                    return '';
4557
                }
4558
4559 11
                $str_length -= (int) $bom_byte_length;
4560
4561 55
                $str = (string) $str_tmp;
4562
            }
4563
        }
4564
4565 55
        return $str;
4566
    }
4567
4568
    /**
4569
     * Removes duplicate occurrences of a string in another string.
4570
     *
4571
     * @param string          $str  <p>The base string.</p>
4572
     * @param string|string[] $what <p>String to search for in the base string.</p>
4573
     *
4574
     * @return string the result string with removed duplicates
4575
     */
4576 2
    public static function remove_duplicates(string $str, $what = ' '): string
4577
    {
4578 2
        if (\is_string($what) === true) {
4579 2
            $what = [$what];
4580
        }
4581
4582 2
        if (\is_array($what) === true) {
0 ignored issues
show
introduced by
The condition is_array($what) === true is always true.
Loading history...
4583
            /** @noinspection ForeachSourceInspection */
4584 2
            foreach ($what as $item) {
4585 2
                $str = (string) \preg_replace('/(' . \preg_quote($item, '/u') . ')+/u', $item, $str);
4586
            }
4587
        }
4588
4589 2
        return $str;
4590
    }
4591
4592
    /**
4593
     * Remove html via "strip_tags()" from the string.
4594
     *
4595
     * @param string $str
4596
     * @param string $allowable_tags [optional] <p>You can use the optional second parameter to specify tags which should
4597
     *                               not be stripped. Default: null
4598
     *                               </p>
4599
     *
4600
     * @return string
4601
     */
4602 6
    public static function remove_html(string $str, string $allowable_tags = ''): string
4603
    {
4604 6
        return \strip_tags($str, $allowable_tags);
4605
    }
4606
4607
    /**
4608
     * Remove all breaks [<br> | \r\n | \r | \n | ...] from the string.
4609
     *
4610
     * @param string $str
4611
     * @param string $replacement [optional] <p>Default is a empty string.</p>
4612
     *
4613
     * @return string
4614
     */
4615 6
    public static function remove_html_breaks(string $str, string $replacement = ''): string
4616
    {
4617 6
        return (string) \preg_replace("#/\r\n|\r|\n|<br.*/?>#isU", $replacement, $str);
4618
    }
4619
4620
    /**
4621
     * Remove invisible characters from a string.
4622
     *
4623
     * e.g.: This prevents sandwiching null characters between ascii characters, like Java\0script.
4624
     *
4625
     * copy&past from https://github.com/bcit-ci/CodeIgniter/blob/develop/system/core/Common.php
4626
     *
4627
     * @param string $str
4628
     * @param bool   $url_encoded
4629
     * @param string $replacement
4630
     *
4631
     * @return string
4632
     */
4633 89
    public static function remove_invisible_characters(
4634
        string $str,
4635
        bool $url_encoded = true,
4636
        string $replacement = ''
4637
    ): string {
4638 89
        return ASCII::remove_invisible_characters(
4639 89
            $str,
4640 89
            $url_encoded,
4641 89
            $replacement
4642
        );
4643
    }
4644
4645
    /**
4646
     * Returns a new string with the prefix $substring removed, if present.
4647
     *
4648
     * @param string $str
4649
     * @param string $substring <p>The prefix to remove.</p>
4650
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
4651
     *
4652
     * @return string string without the prefix $substring
4653
     */
4654 12
    public static function remove_left(
4655
        string $str,
4656
        string $substring,
4657
        string $encoding = 'UTF-8'
4658
    ): string {
4659 12
        if ($substring && \strpos($str, $substring) === 0) {
4660 6
            if ($encoding === 'UTF-8') {
4661 4
                return (string) \mb_substr(
4662 4
                    $str,
4663 4
                    (int) \mb_strlen($substring)
4664
                );
4665
            }
4666
4667 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
4668
4669 2
            return (string) self::substr(
4670 2
                $str,
4671 2
                (int) self::strlen($substring, $encoding),
4672 2
                null,
4673 2
                $encoding
4674
            );
4675
        }
4676
4677 6
        return $str;
4678
    }
4679
4680
    /**
4681
     * Returns a new string with the suffix $substring removed, if present.
4682
     *
4683
     * @param string $str
4684
     * @param string $substring <p>The suffix to remove.</p>
4685
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
4686
     *
4687
     * @return string string having a $str without the suffix $substring
4688
     */
4689 12
    public static function remove_right(
4690
        string $str,
4691
        string $substring,
4692
        string $encoding = 'UTF-8'
4693
    ): string {
4694 12
        if ($substring && \substr($str, -\strlen($substring)) === $substring) {
4695 6
            if ($encoding === 'UTF-8') {
4696 4
                return (string) \mb_substr(
4697 4
                    $str,
4698 4
                    0,
4699 4
                    (int) \mb_strlen($str) - (int) \mb_strlen($substring)
4700
                );
4701
            }
4702
4703 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
4704
4705 2
            return (string) self::substr(
4706 2
                $str,
4707 2
                0,
4708 2
                (int) self::strlen($str, $encoding) - (int) self::strlen($substring, $encoding),
4709 2
                $encoding
4710
            );
4711
        }
4712
4713 6
        return $str;
4714
    }
4715
4716
    /**
4717
     * Replaces all occurrences of $search in $str by $replacement.
4718
     *
4719
     * @param string $str            <p>The input string.</p>
4720
     * @param string $search         <p>The needle to search for.</p>
4721
     * @param string $replacement    <p>The string to replace with.</p>
4722
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
4723
     *
4724
     * @return string string after the replacements
4725
     */
4726 29
    public static function replace(
4727
        string $str,
4728
        string $search,
4729
        string $replacement,
4730
        bool $case_sensitive = true
4731
    ): string {
4732 29
        if ($case_sensitive) {
4733 22
            return \str_replace($search, $replacement, $str);
4734
        }
4735
4736 7
        return self::str_ireplace($search, $replacement, $str);
4737
    }
4738
4739
    /**
4740
     * Replaces all occurrences of $search in $str by $replacement.
4741
     *
4742
     * @param string       $str            <p>The input string.</p>
4743
     * @param array        $search         <p>The elements to search for.</p>
4744
     * @param array|string $replacement    <p>The string to replace with.</p>
4745
     * @param bool         $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
4746
     *
4747
     * @return string string after the replacements
4748
     */
4749 30
    public static function replace_all(
4750
        string $str,
4751
        array $search,
4752
        $replacement,
4753
        bool $case_sensitive = true
4754
    ): string {
4755 30
        if ($case_sensitive) {
4756 23
            return \str_replace($search, $replacement, $str);
4757
        }
4758
4759 7
        return self::str_ireplace($search, $replacement, $str);
4760
    }
4761
4762
    /**
4763
     * Replace the diamond question mark (�) and invalid-UTF8 chars with the replacement.
4764
     *
4765
     * @param string $str                        <p>The input string</p>
4766
     * @param string $replacement_char           <p>The replacement character.</p>
4767
     * @param bool   $process_invalid_utf8_chars <p>Convert invalid UTF-8 chars </p>
4768
     *
4769
     * @return string
4770
     */
4771 35
    public static function replace_diamond_question_mark(
4772
        string $str,
4773
        string $replacement_char = '',
4774
        bool $process_invalid_utf8_chars = true
4775
    ): string {
4776 35
        if ($str === '') {
4777 9
            return '';
4778
        }
4779
4780 35
        if ($process_invalid_utf8_chars === true) {
4781 35
            $replacement_char_helper = $replacement_char;
4782 35
            if ($replacement_char === '') {
4783 35
                $replacement_char_helper = 'none';
4784
            }
4785
4786 35
            if (self::$SUPPORT['mbstring'] === false) {
4787
                // if there is no native support for "mbstring",
4788
                // then we need to clean the string before ...
4789
                $str = self::clean($str);
4790
            }
4791
4792 35
            $save = \mb_substitute_character();
4793 35
            \mb_substitute_character($replacement_char_helper);
4794
            // the polyfill maybe return false, so cast to string
4795 35
            $str = (string) \mb_convert_encoding($str, 'UTF-8', 'UTF-8');
4796 35
            \mb_substitute_character($save);
4797
        }
4798
4799 35
        return \str_replace(
4800
            [
4801 35
                "\xEF\xBF\xBD",
4802
                '�',
4803
            ],
4804
            [
4805 35
                $replacement_char,
4806 35
                $replacement_char,
4807
            ],
4808 35
            $str
4809
        );
4810
    }
4811
4812
    /**
4813
     * Strip whitespace or other characters from the end of a UTF-8 string.
4814
     *
4815
     * @param string      $str   <p>The string to be trimmed.</p>
4816
     * @param string|null $chars <p>Optional characters to be stripped.</p>
4817
     *
4818
     * @return string the string with unwanted characters stripped from the right
4819
     */
4820 20
    public static function rtrim(string $str = '', string $chars = null): string
4821
    {
4822 20
        if ($str === '') {
4823 3
            return '';
4824
        }
4825
4826 19
        if ($chars) {
4827 8
            $chars = \preg_quote($chars, '/');
4828 8
            $pattern = "[${chars}]+$";
4829
        } else {
4830 14
            $pattern = '[\\s]+$';
4831
        }
4832
4833 19
        if (self::$SUPPORT['mbstring'] === true) {
4834
            /** @noinspection PhpComposerExtensionStubsInspection */
4835 19
            return (string) \mb_ereg_replace($pattern, '', $str);
4836
        }
4837
4838
        return self::regex_replace($str, $pattern, '', '', '/');
4839
    }
4840
4841
    /**
4842
     * WARNING: Print native UTF-8 support (libs), e.g. for debugging.
4843
     *
4844
     * @psalm-suppress MissingReturnType
4845
     */
4846 2
    public static function showSupport()
4847
    {
4848 2
        echo '<pre>';
4849 2
        foreach (self::$SUPPORT as $key => &$value) {
4850 2
            echo $key . ' - ' . \print_r($value, true) . "\n<br>";
4851
        }
4852 2
        unset($value);
4853 2
        echo '</pre>';
4854 2
    }
4855
4856
    /**
4857
     * Converts a UTF-8 character to HTML Numbered Entity like "&#123;".
4858
     *
4859
     * @param string $char             <p>The Unicode character to be encoded as numbered entity.</p>
4860
     * @param bool   $keep_ascii_chars <p>Set to <strong>true</strong> to keep ASCII chars.</>
4861
     * @param string $encoding         [optional] <p>Set the charset for e.g. "mb_" function</p>
4862
     *
4863
     * @return string the HTML numbered entity
4864
     */
4865 2
    public static function single_chr_html_encode(
4866
        string $char,
4867
        bool $keep_ascii_chars = false,
4868
        string $encoding = 'UTF-8'
4869
    ): string {
4870 2
        if ($char === '') {
4871 2
            return '';
4872
        }
4873
4874
        if (
4875 2
            $keep_ascii_chars === true
4876
            &&
4877 2
            ASCII::is_ascii($char) === true
4878
        ) {
4879 2
            return $char;
4880
        }
4881
4882 2
        return '&#' . self::ord($char, $encoding) . ';';
4883
    }
4884
4885
    /**
4886
     * @param string $str
4887
     * @param int    $tab_length
4888
     *
4889
     * @return string
4890
     */
4891 5
    public static function spaces_to_tabs(string $str, int $tab_length = 4): string
4892
    {
4893 5
        if ($tab_length === 4) {
4894 3
            $tab = '    ';
4895 2
        } elseif ($tab_length === 2) {
4896 1
            $tab = '  ';
4897
        } else {
4898 1
            $tab = \str_repeat(' ', $tab_length);
4899
        }
4900
4901 5
        return \str_replace($tab, "\t", $str);
4902
    }
4903
4904
    /**
4905
     * alias for "UTF8::str_split()"
4906
     *
4907
     * @param string|string[] $str
4908
     * @param int             $length
4909
     * @param bool            $clean_utf8
4910
     *
4911
     * @return string[]
4912
     *
4913
     * @see UTF8::str_split()
4914
     * @deprecated <p>please use "UTF8::str_split()"</p>
4915
     */
4916 9
    public static function split(
4917
        $str,
4918
        int $length = 1,
4919
        bool $clean_utf8 = false
4920
    ): array {
4921 9
        return self::str_split($str, $length, $clean_utf8);
4922
    }
4923
4924
    /**
4925
     * alias for "UTF8::str_starts_with()"
4926
     *
4927
     * @param string $haystack
4928
     * @param string $needle
4929
     *
4930
     * @return bool
4931
     *
4932
     * @see UTF8::str_starts_with()
4933
     * @deprecated <p>please use "UTF8::str_starts_with()"</p>
4934
     */
4935
    public static function str_begins(string $haystack, string $needle): bool
4936
    {
4937
        return self::str_starts_with($haystack, $needle);
4938
    }
4939
4940
    /**
4941
     * Returns a camelCase version of the string. Trims surrounding spaces,
4942
     * capitalizes letters following digits, spaces, dashes and underscores,
4943
     * and removes spaces, dashes, as well as underscores.
4944
     *
4945
     * @param string      $str                           <p>The input string.</p>
4946
     * @param string      $encoding                      [optional] <p>Default: 'UTF-8'</p>
4947
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
4948
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt, tr</p>
4949
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
4950
     *
4951
     * @return string
4952
     */
4953 32
    public static function str_camelize(
4954
        string $str,
4955
        string $encoding = 'UTF-8',
4956
        bool $clean_utf8 = false,
4957
        string $lang = null,
4958
        bool $try_to_keep_the_string_length = false
4959
    ): string {
4960 32
        if ($clean_utf8 === true) {
4961
            $str = self::clean($str);
4962
        }
4963
4964 32
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
4965 26
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
4966
        }
4967
4968 32
        $str = self::lcfirst(
4969 32
            \trim($str),
4970 32
            $encoding,
4971 32
            false,
4972 32
            $lang,
4973 32
            $try_to_keep_the_string_length
4974
        );
4975 32
        $str = (string) \preg_replace('/^[-_]+/', '', $str);
4976
4977 32
        $use_mb_functions = $lang === null && $try_to_keep_the_string_length === false;
4978
4979 32
        $str = (string) \preg_replace_callback(
4980 32
            '/[-_\\s]+(.)?/u',
4981
            /**
4982
             * @param array $match
4983
             *
4984
             * @return string
4985
             */
4986
            static function (array $match) use ($use_mb_functions, $encoding, $lang, $try_to_keep_the_string_length): string {
4987 27
                if (isset($match[1])) {
4988 27
                    if ($use_mb_functions === true) {
4989 27
                        if ($encoding === 'UTF-8') {
4990 27
                            return \mb_strtoupper($match[1]);
4991
                        }
4992
4993
                        return \mb_strtoupper($match[1], $encoding);
4994
                    }
4995
4996
                    return self::strtoupper($match[1], $encoding, false, $lang, $try_to_keep_the_string_length);
4997
                }
4998
4999 1
                return '';
5000 32
            },
5001 32
            $str
5002
        );
5003
5004 32
        return (string) \preg_replace_callback(
5005 32
            '/[\\p{N}]+(.)?/u',
5006
            /**
5007
             * @param array $match
5008
             *
5009
             * @return string
5010
             */
5011
            static function (array $match) use ($use_mb_functions, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length): string {
5012 6
                if ($use_mb_functions === true) {
5013 6
                    if ($encoding === 'UTF-8') {
5014 6
                        return \mb_strtoupper($match[0]);
5015
                    }
5016
5017
                    return \mb_strtoupper($match[0], $encoding);
5018
                }
5019
5020
                return self::strtoupper($match[0], $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
5021 32
            },
5022 32
            $str
5023
        );
5024
    }
5025
5026
    /**
5027
     * Returns the string with the first letter of each word capitalized,
5028
     * except for when the word is a name which shouldn't be capitalized.
5029
     *
5030
     * @param string $str
5031
     *
5032
     * @return string string with $str capitalized
5033
     */
5034 1
    public static function str_capitalize_name(string $str): string
5035
    {
5036 1
        return self::str_capitalize_name_helper(
5037 1
            self::str_capitalize_name_helper(
5038 1
                self::collapse_whitespace($str),
5039 1
                ' '
5040
            ),
5041 1
            '-'
5042
        );
5043
    }
5044
5045
    /**
5046
     * Returns true if the string contains $needle, false otherwise. By default
5047
     * the comparison is case-sensitive, but can be made insensitive by setting
5048
     * $case_sensitive to false.
5049
     *
5050
     * @param string $haystack       <p>The input string.</p>
5051
     * @param string $needle         <p>Substring to look for.</p>
5052
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5053
     *
5054
     * @return bool whether or not $haystack contains $needle
5055
     */
5056 21
    public static function str_contains(
5057
        string $haystack,
5058
        string $needle,
5059
        bool $case_sensitive = true
5060
    ): bool {
5061 21
        if ($case_sensitive) {
5062 11
            return \strpos($haystack, $needle) !== false;
5063
        }
5064
5065 10
        return \mb_stripos($haystack, $needle) !== false;
5066
    }
5067
5068
    /**
5069
     * Returns true if the string contains all $needles, false otherwise. By
5070
     * default the comparison is case-sensitive, but can be made insensitive by
5071
     * setting $case_sensitive to false.
5072
     *
5073
     * @param string $haystack       <p>The input string.</p>
5074
     * @param array  $needles        <p>SubStrings to look for.</p>
5075
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5076
     *
5077
     * @return bool whether or not $haystack contains $needle
5078
     */
5079 44
    public static function str_contains_all(
5080
        string $haystack,
5081
        array $needles,
5082
        bool $case_sensitive = true
5083
    ): bool {
5084 44
        if ($haystack === '' || $needles === []) {
5085 1
            return false;
5086
        }
5087
5088
        /** @noinspection LoopWhichDoesNotLoopInspection */
5089 43
        foreach ($needles as &$needle) {
5090 43
            if (!$needle) {
5091 1
                return false;
5092
            }
5093
5094 42
            if ($case_sensitive) {
5095 22
                return \strpos($haystack, $needle) !== false;
5096
            }
5097
5098 20
            return \mb_stripos($haystack, $needle) !== false;
5099
        }
5100
5101
        return true;
5102
    }
5103
5104
    /**
5105
     * Returns true if the string contains any $needles, false otherwise. By
5106
     * default the comparison is case-sensitive, but can be made insensitive by
5107
     * setting $case_sensitive to false.
5108
     *
5109
     * @param string $haystack       <p>The input string.</p>
5110
     * @param array  $needles        <p>SubStrings to look for.</p>
5111
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5112
     *
5113
     * @return bool
5114
     *              Whether or not $str contains $needle
5115
     */
5116 46
    public static function str_contains_any(
5117
        string $haystack,
5118
        array $needles,
5119
        bool $case_sensitive = true
5120
    ): bool {
5121 46
        if ($haystack === '' || $needles === []) {
5122 1
            return false;
5123
        }
5124
5125
        /** @noinspection LoopWhichDoesNotLoopInspection */
5126 45
        foreach ($needles as &$needle) {
5127 45
            if (!$needle) {
5128
                continue;
5129
            }
5130
5131 45
            if ($case_sensitive) {
5132 25
                if (\strpos($haystack, $needle) !== false) {
5133 14
                    return true;
5134
                }
5135
5136 13
                continue;
5137
            }
5138
5139 20
            if (\mb_stripos($haystack, $needle) !== false) {
5140 20
                return true;
5141
            }
5142
        }
5143
5144 19
        return false;
5145
    }
5146
5147
    /**
5148
     * Returns a lowercase and trimmed string separated by dashes. Dashes are
5149
     * inserted before uppercase characters (with the exception of the first
5150
     * character of the string), and in place of spaces as well as underscores.
5151
     *
5152
     * @param string $str      <p>The input string.</p>
5153
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
5154
     *
5155
     * @return string
5156
     */
5157 19
    public static function str_dasherize(string $str, string $encoding = 'UTF-8'): string
5158
    {
5159 19
        return self::str_delimit($str, '-', $encoding);
5160
    }
5161
5162
    /**
5163
     * Returns a lowercase and trimmed string separated by the given delimiter.
5164
     * Delimiters are inserted before uppercase characters (with the exception
5165
     * of the first character of the string), and in place of spaces, dashes,
5166
     * and underscores. Alpha delimiters are not converted to lowercase.
5167
     *
5168
     * @param string      $str                           <p>The input string.</p>
5169
     * @param string      $delimiter                     <p>Sequence used to separate parts of the string.</p>
5170
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
5171
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
5172
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
5173
     *                                                   tr</p>
5174
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ ->
5175
     *                                                   ß</p>
5176
     *
5177
     * @return string
5178
     */
5179 49
    public static function str_delimit(
5180
        string $str,
5181
        string $delimiter,
5182
        string $encoding = 'UTF-8',
5183
        bool $clean_utf8 = false,
5184
        string $lang = null,
5185
        bool $try_to_keep_the_string_length = false
5186
    ): string {
5187 49
        if (self::$SUPPORT['mbstring'] === true) {
5188
            /** @noinspection PhpComposerExtensionStubsInspection */
5189 49
            $str = (string) \mb_ereg_replace('\\B(\\p{Lu})', '-\1', \trim($str));
5190
5191 49
            $use_mb_functions = $lang === null && $try_to_keep_the_string_length === false;
5192 49
            if ($use_mb_functions === true && $encoding === 'UTF-8') {
5193 22
                $str = \mb_strtolower($str);
5194
            } else {
5195 27
                $str = self::strtolower($str, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
5196
            }
5197
5198
            /** @noinspection PhpComposerExtensionStubsInspection */
5199 49
            return (string) \mb_ereg_replace('[\\-_\\s]+', $delimiter, $str);
5200
        }
5201
5202
        $str = (string) \preg_replace('/\\B(\\p{Lu})/u', '-\1', \trim($str));
5203
5204
        $use_mb_functions = $lang === null && $try_to_keep_the_string_length === false;
5205
        if ($use_mb_functions === true && $encoding === 'UTF-8') {
5206
            $str = \mb_strtolower($str);
5207
        } else {
5208
            $str = self::strtolower($str, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
5209
        }
5210
5211
        return (string) \preg_replace('/[\\-_\\s]+/u', $delimiter, $str);
5212
    }
5213
5214
    /**
5215
     * Optimized "mb_detect_encoding()"-function -> with support for UTF-16 and UTF-32.
5216
     *
5217
     * @param string $str <p>The input string.</p>
5218
     *
5219
     * @return false|string
5220
     *                      The detected string-encoding e.g. UTF-8 or UTF-16BE,<br>
5221
     *                      otherwise it will return false e.g. for BINARY or not detected encoding.
5222
     */
5223 30
    public static function str_detect_encoding($str)
5224
    {
5225
        // init
5226 30
        $str = (string) $str;
5227
5228
        //
5229
        // 1.) check binary strings (010001001...) like UTF-16 / UTF-32 / PDF / Images / ...
5230
        //
5231
5232 30
        if (self::is_binary($str, true) === true) {
5233 11
            $is_utf32 = self::is_utf32($str, false);
5234 11
            if ($is_utf32 === 1) {
5235
                return 'UTF-32LE';
5236
            }
5237 11
            if ($is_utf32 === 2) {
5238 1
                return 'UTF-32BE';
5239
            }
5240
5241 11
            $is_utf16 = self::is_utf16($str, false);
5242 11
            if ($is_utf16 === 1) {
5243 3
                return 'UTF-16LE';
5244
            }
5245 11
            if ($is_utf16 === 2) {
5246 2
                return 'UTF-16BE';
5247
            }
5248
5249
            // is binary but not "UTF-16" or "UTF-32"
5250 9
            return false;
5251
        }
5252
5253
        //
5254
        // 2.) simple check for ASCII chars
5255
        //
5256
5257 26
        if (ASCII::is_ascii($str) === true) {
5258 10
            return 'ASCII';
5259
        }
5260
5261
        //
5262
        // 3.) simple check for UTF-8 chars
5263
        //
5264
5265 26
        if (self::is_utf8_string($str) === true) {
5266 19
            return 'UTF-8';
5267
        }
5268
5269
        //
5270
        // 4.) check via "mb_detect_encoding()"
5271
        //
5272
        // INFO: UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always with "mb_detect_encoding()"
5273
5274
        $encoding_detecting_order = [
5275 15
            'ISO-8859-1',
5276
            'ISO-8859-2',
5277
            'ISO-8859-3',
5278
            'ISO-8859-4',
5279
            'ISO-8859-5',
5280
            'ISO-8859-6',
5281
            'ISO-8859-7',
5282
            'ISO-8859-8',
5283
            'ISO-8859-9',
5284
            'ISO-8859-10',
5285
            'ISO-8859-13',
5286
            'ISO-8859-14',
5287
            'ISO-8859-15',
5288
            'ISO-8859-16',
5289
            'WINDOWS-1251',
5290
            'WINDOWS-1252',
5291
            'WINDOWS-1254',
5292
            'CP932',
5293
            'CP936',
5294
            'CP950',
5295
            'CP866',
5296
            'CP850',
5297
            'CP51932',
5298
            'CP50220',
5299
            'CP50221',
5300
            'CP50222',
5301
            'ISO-2022-JP',
5302
            'ISO-2022-KR',
5303
            'JIS',
5304
            'JIS-ms',
5305
            'EUC-CN',
5306
            'EUC-JP',
5307
        ];
5308
5309 15
        if (self::$SUPPORT['mbstring'] === true) {
5310
            // info: do not use the symfony polyfill here
5311 15
            $encoding = \mb_detect_encoding($str, $encoding_detecting_order, true);
5312 15
            if ($encoding) {
5313 15
                return $encoding;
5314
            }
5315
        }
5316
5317
        //
5318
        // 5.) check via "iconv()"
5319
        //
5320
5321
        if (self::$ENCODINGS === null) {
5322
            self::$ENCODINGS = self::getData('encodings');
5323
        }
5324
5325
        foreach (self::$ENCODINGS as $encoding_tmp) {
5326
            // INFO: //IGNORE but still throw notice
5327
            /** @noinspection PhpUsageOfSilenceOperatorInspection */
5328
            if ((string) @\iconv($encoding_tmp, $encoding_tmp . '//IGNORE', $str) === $str) {
5329
                return $encoding_tmp;
5330
            }
5331
        }
5332
5333
        return false;
5334
    }
5335
5336
    /**
5337
     * alias for "UTF8::str_ends_with()"
5338
     *
5339
     * @param string $haystack
5340
     * @param string $needle
5341
     *
5342
     * @return bool
5343
     *
5344
     * @see UTF8::str_ends_with()
5345
     * @deprecated <p>please use "UTF8::str_ends_with()"</p>
5346
     */
5347
    public static function str_ends(string $haystack, string $needle): bool
5348
    {
5349
        return self::str_ends_with($haystack, $needle);
5350
    }
5351
5352
    /**
5353
     * Check if the string ends with the given substring.
5354
     *
5355
     * @param string $haystack <p>The string to search in.</p>
5356
     * @param string $needle   <p>The substring to search for.</p>
5357
     *
5358
     * @return bool
5359
     */
5360 9
    public static function str_ends_with(string $haystack, string $needle): bool
5361
    {
5362 9
        if ($needle === '') {
5363 2
            return true;
5364
        }
5365
5366 9
        if ($haystack === '') {
5367
            return false;
5368
        }
5369
5370 9
        return \substr($haystack, -\strlen($needle)) === $needle;
5371
    }
5372
5373
    /**
5374
     * Returns true if the string ends with any of $substrings, false otherwise.
5375
     *
5376
     * - case-sensitive
5377
     *
5378
     * @param string   $str        <p>The input string.</p>
5379
     * @param string[] $substrings <p>Substrings to look for.</p>
5380
     *
5381
     * @return bool whether or not $str ends with $substring
5382
     */
5383 7
    public static function str_ends_with_any(string $str, array $substrings): bool
5384
    {
5385 7
        if ($substrings === []) {
5386
            return false;
5387
        }
5388
5389 7
        foreach ($substrings as &$substring) {
5390 7
            if (\substr($str, -\strlen($substring)) === $substring) {
5391 7
                return true;
5392
            }
5393
        }
5394
5395 6
        return false;
5396
    }
5397
5398
    /**
5399
     * Ensures that the string begins with $substring. If it doesn't, it's
5400
     * prepended.
5401
     *
5402
     * @param string $str       <p>The input string.</p>
5403
     * @param string $substring <p>The substring to add if not present.</p>
5404
     *
5405
     * @return string
5406
     */
5407 10
    public static function str_ensure_left(string $str, string $substring): string
5408
    {
5409
        if (
5410 10
            $substring !== ''
5411
            &&
5412 10
            \strpos($str, $substring) === 0
5413
        ) {
5414 6
            return $str;
5415
        }
5416
5417 4
        return $substring . $str;
5418
    }
5419
5420
    /**
5421
     * Ensures that the string ends with $substring. If it doesn't, it's appended.
5422
     *
5423
     * @param string $str       <p>The input string.</p>
5424
     * @param string $substring <p>The substring to add if not present.</p>
5425
     *
5426
     * @return string
5427
     */
5428 10
    public static function str_ensure_right(string $str, string $substring): string
5429
    {
5430
        if (
5431 10
            $str === ''
5432
            ||
5433 10
            $substring === ''
5434
            ||
5435 10
            \substr($str, -\strlen($substring)) !== $substring
5436
        ) {
5437 4
            $str .= $substring;
5438
        }
5439
5440 10
        return $str;
5441
    }
5442
5443
    /**
5444
     * Capitalizes the first word of the string, replaces underscores with
5445
     * spaces, and strips '_id'.
5446
     *
5447
     * @param string $str
5448
     *
5449
     * @return string
5450
     */
5451 3
    public static function str_humanize($str): string
5452
    {
5453 3
        $str = \str_replace(
5454
            [
5455 3
                '_id',
5456
                '_',
5457
            ],
5458
            [
5459 3
                '',
5460
                ' ',
5461
            ],
5462 3
            $str
5463
        );
5464
5465 3
        return self::ucfirst(\trim($str));
5466
    }
5467
5468
    /**
5469
     * alias for "UTF8::str_istarts_with()"
5470
     *
5471
     * @param string $haystack
5472
     * @param string $needle
5473
     *
5474
     * @return bool
5475
     *
5476
     * @see UTF8::str_istarts_with()
5477
     * @deprecated <p>please use "UTF8::str_istarts_with()"</p>
5478
     */
5479
    public static function str_ibegins(string $haystack, string $needle): bool
5480
    {
5481
        return self::str_istarts_with($haystack, $needle);
5482
    }
5483
5484
    /**
5485
     * alias for "UTF8::str_iends_with()"
5486
     *
5487
     * @param string $haystack
5488
     * @param string $needle
5489
     *
5490
     * @return bool
5491
     *
5492
     * @see UTF8::str_iends_with()
5493
     * @deprecated <p>please use "UTF8::str_iends_with()"</p>
5494
     */
5495
    public static function str_iends(string $haystack, string $needle): bool
5496
    {
5497
        return self::str_iends_with($haystack, $needle);
5498
    }
5499
5500
    /**
5501
     * Check if the string ends with the given substring, case-insensitive.
5502
     *
5503
     * @param string $haystack <p>The string to search in.</p>
5504
     * @param string $needle   <p>The substring to search for.</p>
5505
     *
5506
     * @return bool
5507
     */
5508 12
    public static function str_iends_with(string $haystack, string $needle): bool
5509
    {
5510 12
        if ($needle === '') {
5511 2
            return true;
5512
        }
5513
5514 12
        if ($haystack === '') {
5515
            return false;
5516
        }
5517
5518 12
        return self::strcasecmp(\substr($haystack, -\strlen($needle)), $needle) === 0;
5519
    }
5520
5521
    /**
5522
     * Returns true if the string ends with any of $substrings, false otherwise.
5523
     *
5524
     * - case-insensitive
5525
     *
5526
     * @param string   $str        <p>The input string.</p>
5527
     * @param string[] $substrings <p>Substrings to look for.</p>
5528
     *
5529
     * @return bool whether or not $str ends with $substring
5530
     */
5531 4
    public static function str_iends_with_any(string $str, array $substrings): bool
5532
    {
5533 4
        if ($substrings === []) {
5534
            return false;
5535
        }
5536
5537 4
        foreach ($substrings as &$substring) {
5538 4
            if (self::str_iends_with($str, $substring)) {
5539 4
                return true;
5540
            }
5541
        }
5542
5543
        return false;
5544
    }
5545
5546
    /**
5547
     * Returns the index of the first occurrence of $needle in the string,
5548
     * and false if not found. Accepts an optional offset from which to begin
5549
     * the search.
5550
     *
5551
     * @param string $str      <p>The input string.</p>
5552
     * @param string $needle   <p>Substring to look for.</p>
5553
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5554
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
5555
     *
5556
     * @return false|int
5557
     *                   The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>
5558
     */
5559 2
    public static function str_iindex_first(
5560
        string $str,
5561
        string $needle,
5562
        int $offset = 0,
5563
        string $encoding = 'UTF-8'
5564
    ) {
5565 2
        return self::stripos(
5566 2
            $str,
5567 2
            $needle,
5568 2
            $offset,
5569 2
            $encoding
5570
        );
5571
    }
5572
5573
    /**
5574
     * Returns the index of the last occurrence of $needle in the string,
5575
     * and false if not found. Accepts an optional offset from which to begin
5576
     * the search. Offsets may be negative to count from the last character
5577
     * in the string.
5578
     *
5579
     * @param string $str      <p>The input string.</p>
5580
     * @param string $needle   <p>Substring to look for.</p>
5581
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5582
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
5583
     *
5584
     * @return false|int
5585
     *                   The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>
5586
     */
5587
    public static function str_iindex_last(
5588
        string $str,
5589
        string $needle,
5590
        int $offset = 0,
5591
        string $encoding = 'UTF-8'
5592
    ) {
5593
        return self::strripos(
5594
            $str,
5595
            $needle,
5596
            $offset,
5597
            $encoding
5598
        );
5599
    }
5600
5601
    /**
5602
     * Returns the index of the first occurrence of $needle in the string,
5603
     * and false if not found. Accepts an optional offset from which to begin
5604
     * the search.
5605
     *
5606
     * @param string $str      <p>The input string.</p>
5607
     * @param string $needle   <p>Substring to look for.</p>
5608
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5609
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
5610
     *
5611
     * @return false|int
5612
     *                   The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>
5613
     */
5614 10
    public static function str_index_first(
5615
        string $str,
5616
        string $needle,
5617
        int $offset = 0,
5618
        string $encoding = 'UTF-8'
5619
    ) {
5620 10
        return self::strpos(
5621 10
            $str,
5622 10
            $needle,
5623 10
            $offset,
5624 10
            $encoding
5625
        );
5626
    }
5627
5628
    /**
5629
     * Returns the index of the last occurrence of $needle in the string,
5630
     * and false if not found. Accepts an optional offset from which to begin
5631
     * the search. Offsets may be negative to count from the last character
5632
     * in the string.
5633
     *
5634
     * @param string $str      <p>The input string.</p>
5635
     * @param string $needle   <p>Substring to look for.</p>
5636
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5637
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
5638
     *
5639
     * @return false|int
5640
     *                   The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>
5641
     */
5642 10
    public static function str_index_last(
5643
        string $str,
5644
        string $needle,
5645
        int $offset = 0,
5646
        string $encoding = 'UTF-8'
5647
    ) {
5648 10
        return self::strrpos(
5649 10
            $str,
5650 10
            $needle,
5651 10
            $offset,
5652 10
            $encoding
5653
        );
5654
    }
5655
5656
    /**
5657
     * Inserts $substring into the string at the $index provided.
5658
     *
5659
     * @param string $str       <p>The input string.</p>
5660
     * @param string $substring <p>String to be inserted.</p>
5661
     * @param int    $index     <p>The index at which to insert the substring.</p>
5662
     * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
5663
     *
5664
     * @return string
5665
     */
5666 8
    public static function str_insert(
5667
        string $str,
5668
        string $substring,
5669
        int $index,
5670
        string $encoding = 'UTF-8'
5671
    ): string {
5672 8
        if ($encoding === 'UTF-8') {
5673 4
            $len = (int) \mb_strlen($str);
5674 4
            if ($index > $len) {
5675
                return $str;
5676
            }
5677
5678
            /** @noinspection UnnecessaryCastingInspection */
5679 4
            return (string) \mb_substr($str, 0, $index) .
5680 4
                   $substring .
5681 4
                   (string) \mb_substr($str, $index, $len);
5682
        }
5683
5684 4
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
5685
5686 4
        $len = (int) self::strlen($str, $encoding);
5687 4
        if ($index > $len) {
5688 1
            return $str;
5689
        }
5690
5691 3
        return ((string) self::substr($str, 0, $index, $encoding)) .
5692 3
               $substring .
5693 3
               ((string) self::substr($str, $index, $len, $encoding));
5694
    }
5695
5696
    /**
5697
     * Case-insensitive and UTF-8 safe version of <function>str_replace</function>.
5698
     *
5699
     * @see http://php.net/manual/en/function.str-ireplace.php
5700
     *
5701
     * @param mixed $search  <p>
5702
     *                       Every replacement with search array is
5703
     *                       performed on the result of previous replacement.
5704
     *                       </p>
5705
     * @param mixed $replace <p>
5706
     *                       </p>
5707
     * @param mixed $subject <p>
5708
     *                       If subject is an array, then the search and
5709
     *                       replace is performed with every entry of
5710
     *                       subject, and the return value is an array as
5711
     *                       well.
5712
     *                       </p>
5713
     * @param int   $count   [optional] <p>
5714
     *                       The number of matched and replaced needles will
5715
     *                       be returned in count which is passed by
5716
     *                       reference.
5717
     *                       </p>
5718
     *
5719
     * @return mixed a string or an array of replacements
5720
     */
5721 29
    public static function str_ireplace($search, $replace, $subject, &$count = null)
5722
    {
5723 29
        $search = (array) $search;
5724
5725
        /** @noinspection AlterInForeachInspection */
5726 29
        foreach ($search as &$s) {
5727 29
            $s = (string) $s;
5728 29
            if ($s === '') {
5729 6
                $s = '/^(?<=.)$/';
5730
            } else {
5731 29
                $s = '/' . \preg_quote($s, '/') . '/ui';
5732
            }
5733
        }
5734
5735 29
        $subject = \preg_replace($search, $replace, $subject, -1, $replace);
5736 29
        $count = $replace; // used as reference parameter
5737
5738 29
        return $subject;
5739
    }
5740
5741
    /**
5742
     * Replaces $search from the beginning of string with $replacement.
5743
     *
5744
     * @param string $str         <p>The input string.</p>
5745
     * @param string $search      <p>The string to search for.</p>
5746
     * @param string $replacement <p>The replacement.</p>
5747
     *
5748
     * @return string string after the replacements
5749
     */
5750 17
    public static function str_ireplace_beginning(string $str, string $search, string $replacement): string
5751
    {
5752 17
        if ($str === '') {
5753 4
            if ($replacement === '') {
5754 2
                return '';
5755
            }
5756
5757 2
            if ($search === '') {
5758 2
                return $replacement;
5759
            }
5760
        }
5761
5762 13
        if ($search === '') {
5763 2
            return $str . $replacement;
5764
        }
5765
5766 11
        if (\stripos($str, $search) === 0) {
5767 10
            return $replacement . \substr($str, \strlen($search));
5768
        }
5769
5770 1
        return $str;
5771
    }
5772
5773
    /**
5774
     * Replaces $search from the ending of string with $replacement.
5775
     *
5776
     * @param string $str         <p>The input string.</p>
5777
     * @param string $search      <p>The string to search for.</p>
5778
     * @param string $replacement <p>The replacement.</p>
5779
     *
5780
     * @return string string after the replacements
5781
     */
5782 17
    public static function str_ireplace_ending(string $str, string $search, string $replacement): string
5783
    {
5784 17
        if ($str === '') {
5785 4
            if ($replacement === '') {
5786 2
                return '';
5787
            }
5788
5789 2
            if ($search === '') {
5790 2
                return $replacement;
5791
            }
5792
        }
5793
5794 13
        if ($search === '') {
5795 2
            return $str . $replacement;
5796
        }
5797
5798 11
        if (\stripos($str, $search, \strlen($str) - \strlen($search)) !== false) {
5799 9
            $str = \substr($str, 0, -\strlen($search)) . $replacement;
5800
        }
5801
5802 11
        return $str;
5803
    }
5804
5805
    /**
5806
     * Check if the string starts with the given substring, case-insensitive.
5807
     *
5808
     * @param string $haystack <p>The string to search in.</p>
5809
     * @param string $needle   <p>The substring to search for.</p>
5810
     *
5811
     * @return bool
5812
     */
5813 12
    public static function str_istarts_with(string $haystack, string $needle): bool
5814
    {
5815 12
        if ($needle === '') {
5816 2
            return true;
5817
        }
5818
5819 12
        if ($haystack === '') {
5820
            return false;
5821
        }
5822
5823 12
        return self::stripos($haystack, $needle) === 0;
5824
    }
5825
5826
    /**
5827
     * Returns true if the string begins with any of $substrings, false otherwise.
5828
     *
5829
     * - case-insensitive
5830
     *
5831
     * @param string $str        <p>The input string.</p>
5832
     * @param array  $substrings <p>Substrings to look for.</p>
5833
     *
5834
     * @return bool whether or not $str starts with $substring
5835
     */
5836 4
    public static function str_istarts_with_any(string $str, array $substrings): bool
5837
    {
5838 4
        if ($str === '') {
5839
            return false;
5840
        }
5841
5842 4
        if ($substrings === []) {
5843
            return false;
5844
        }
5845
5846 4
        foreach ($substrings as &$substring) {
5847 4
            if (self::str_istarts_with($str, $substring)) {
5848 4
                return true;
5849
            }
5850
        }
5851
5852
        return false;
5853
    }
5854
5855
    /**
5856
     * Gets the substring after the first occurrence of a separator.
5857
     *
5858
     * @param string $str       <p>The input string.</p>
5859
     * @param string $separator <p>The string separator.</p>
5860
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
5861
     *
5862
     * @return string
5863
     */
5864 1
    public static function str_isubstr_after_first_separator(
5865
        string $str,
5866
        string $separator,
5867
        string $encoding = 'UTF-8'
5868
    ): string {
5869 1
        if ($separator === '' || $str === '') {
5870 1
            return '';
5871
        }
5872
5873 1
        $offset = self::str_iindex_first($str, $separator);
5874 1
        if ($offset === false) {
5875 1
            return '';
5876
        }
5877
5878 1
        if ($encoding === 'UTF-8') {
5879 1
            return (string) \mb_substr(
5880 1
                $str,
5881 1
                $offset + (int) \mb_strlen($separator)
5882
            );
5883
        }
5884
5885
        return (string) self::substr(
5886
            $str,
5887
            $offset + (int) self::strlen($separator, $encoding),
5888
            null,
5889
            $encoding
5890
        );
5891
    }
5892
5893
    /**
5894
     * Gets the substring after the last occurrence of a separator.
5895
     *
5896
     * @param string $str       <p>The input string.</p>
5897
     * @param string $separator <p>The string separator.</p>
5898
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
5899
     *
5900
     * @return string
5901
     */
5902 1
    public static function str_isubstr_after_last_separator(
5903
        string $str,
5904
        string $separator,
5905
        string $encoding = 'UTF-8'
5906
    ): string {
5907 1
        if ($separator === '' || $str === '') {
5908 1
            return '';
5909
        }
5910
5911 1
        $offset = self::strripos($str, $separator);
5912 1
        if ($offset === false) {
5913 1
            return '';
5914
        }
5915
5916 1
        if ($encoding === 'UTF-8') {
5917 1
            return (string) \mb_substr(
5918 1
                $str,
5919 1
                $offset + (int) self::strlen($separator)
5920
            );
5921
        }
5922
5923
        return (string) self::substr(
5924
            $str,
5925
            $offset + (int) self::strlen($separator, $encoding),
5926
            null,
5927
            $encoding
5928
        );
5929
    }
5930
5931
    /**
5932
     * Gets the substring before the first occurrence of a separator.
5933
     *
5934
     * @param string $str       <p>The input string.</p>
5935
     * @param string $separator <p>The string separator.</p>
5936
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
5937
     *
5938
     * @return string
5939
     */
5940 1
    public static function str_isubstr_before_first_separator(
5941
        string $str,
5942
        string $separator,
5943
        string $encoding = 'UTF-8'
5944
    ): string {
5945 1
        if ($separator === '' || $str === '') {
5946 1
            return '';
5947
        }
5948
5949 1
        $offset = self::str_iindex_first($str, $separator);
5950 1
        if ($offset === false) {
5951 1
            return '';
5952
        }
5953
5954 1
        if ($encoding === 'UTF-8') {
5955 1
            return (string) \mb_substr($str, 0, $offset);
5956
        }
5957
5958
        return (string) self::substr($str, 0, $offset, $encoding);
5959
    }
5960
5961
    /**
5962
     * Gets the substring before the last occurrence of a separator.
5963
     *
5964
     * @param string $str       <p>The input string.</p>
5965
     * @param string $separator <p>The string separator.</p>
5966
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
5967
     *
5968
     * @return string
5969
     */
5970 1
    public static function str_isubstr_before_last_separator(
5971
        string $str,
5972
        string $separator,
5973
        string $encoding = 'UTF-8'
5974
    ): string {
5975 1
        if ($separator === '' || $str === '') {
5976 1
            return '';
5977
        }
5978
5979 1
        if ($encoding === 'UTF-8') {
5980 1
            $offset = \mb_strripos($str, $separator);
5981 1
            if ($offset === false) {
5982 1
                return '';
5983
            }
5984
5985 1
            return (string) \mb_substr($str, 0, $offset);
5986
        }
5987
5988
        $offset = self::strripos($str, $separator, 0, $encoding);
5989
        if ($offset === false) {
5990
            return '';
5991
        }
5992
5993
        return (string) self::substr($str, 0, $offset, $encoding);
5994
    }
5995
5996
    /**
5997
     * Gets the substring after (or before via "$before_needle") the first occurrence of the "$needle".
5998
     *
5999
     * @param string $str           <p>The input string.</p>
6000
     * @param string $needle        <p>The string to look for.</p>
6001
     * @param bool   $before_needle [optional] <p>Default: false</p>
6002
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
6003
     *
6004
     * @return string
6005
     */
6006 2
    public static function str_isubstr_first(
6007
        string $str,
6008
        string $needle,
6009
        bool $before_needle = false,
6010
        string $encoding = 'UTF-8'
6011
    ): string {
6012
        if (
6013 2
            $needle === ''
6014
            ||
6015 2
            $str === ''
6016
        ) {
6017 2
            return '';
6018
        }
6019
6020 2
        $part = self::stristr(
6021 2
            $str,
6022 2
            $needle,
6023 2
            $before_needle,
6024 2
            $encoding
6025
        );
6026 2
        if ($part === false) {
6027 2
            return '';
6028
        }
6029
6030 2
        return $part;
6031
    }
6032
6033
    /**
6034
     * Gets the substring after (or before via "$before_needle") the last occurrence of the "$needle".
6035
     *
6036
     * @param string $str           <p>The input string.</p>
6037
     * @param string $needle        <p>The string to look for.</p>
6038
     * @param bool   $before_needle [optional] <p>Default: false</p>
6039
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
6040
     *
6041
     * @return string
6042
     */
6043 1
    public static function str_isubstr_last(
6044
        string $str,
6045
        string $needle,
6046
        bool $before_needle = false,
6047
        string $encoding = 'UTF-8'
6048
    ): string {
6049
        if (
6050 1
            $needle === ''
6051
            ||
6052 1
            $str === ''
6053
        ) {
6054 1
            return '';
6055
        }
6056
6057 1
        $part = self::strrichr(
6058 1
            $str,
6059 1
            $needle,
6060 1
            $before_needle,
6061 1
            $encoding
6062
        );
6063 1
        if ($part === false) {
6064 1
            return '';
6065
        }
6066
6067 1
        return $part;
6068
    }
6069
6070
    /**
6071
     * Returns the last $n characters of the string.
6072
     *
6073
     * @param string $str      <p>The input string.</p>
6074
     * @param int    $n        <p>Number of characters to retrieve from the end.</p>
6075
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6076
     *
6077
     * @return string
6078
     */
6079 12
    public static function str_last_char(
6080
        string $str,
6081
        int $n = 1,
6082
        string $encoding = 'UTF-8'
6083
    ): string {
6084 12
        if ($str === '' || $n <= 0) {
6085 4
            return '';
6086
        }
6087
6088 8
        if ($encoding === 'UTF-8') {
6089 4
            return (string) \mb_substr($str, -$n);
6090
        }
6091
6092 4
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
6093
6094 4
        return (string) self::substr($str, -$n, null, $encoding);
6095
    }
6096
6097
    /**
6098
     * Limit the number of characters in a string.
6099
     *
6100
     * @param string $str        <p>The input string.</p>
6101
     * @param int    $length     [optional] <p>Default: 100</p>
6102
     * @param string $str_add_on [optional] <p>Default: …</p>
6103
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
6104
     *
6105
     * @return string
6106
     */
6107 2
    public static function str_limit(
6108
        string $str,
6109
        int $length = 100,
6110
        string $str_add_on = '…',
6111
        string $encoding = 'UTF-8'
6112
    ): string {
6113 2
        if ($str === '' || $length <= 0) {
6114 2
            return '';
6115
        }
6116
6117 2
        if ($encoding === 'UTF-8') {
6118 2
            if ((int) \mb_strlen($str) <= $length) {
6119 2
                return $str;
6120
            }
6121
6122
            /** @noinspection UnnecessaryCastingInspection */
6123 2
            return (string) \mb_substr($str, 0, $length - (int) self::strlen($str_add_on)) . $str_add_on;
6124
        }
6125
6126
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
6127
6128
        if ((int) self::strlen($str, $encoding) <= $length) {
6129
            return $str;
6130
        }
6131
6132
        return ((string) self::substr($str, 0, $length - (int) self::strlen($str_add_on), $encoding)) . $str_add_on;
6133
    }
6134
6135
    /**
6136
     * Limit the number of characters in a string, but also after the next word.
6137
     *
6138
     * @param string $str        <p>The input string.</p>
6139
     * @param int    $length     [optional] <p>Default: 100</p>
6140
     * @param string $str_add_on [optional] <p>Default: …</p>
6141
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
6142
     *
6143
     * @return string
6144
     */
6145 6
    public static function str_limit_after_word(
6146
        string $str,
6147
        int $length = 100,
6148
        string $str_add_on = '…',
6149
        string $encoding = 'UTF-8'
6150
    ): string {
6151 6
        if ($str === '' || $length <= 0) {
6152 2
            return '';
6153
        }
6154
6155 6
        if ($encoding === 'UTF-8') {
6156
            /** @noinspection UnnecessaryCastingInspection */
6157 2
            if ((int) \mb_strlen($str) <= $length) {
6158 2
                return $str;
6159
            }
6160
6161 2
            if (\mb_substr($str, $length - 1, 1) === ' ') {
6162 2
                return ((string) \mb_substr($str, 0, $length - 1)) . $str_add_on;
6163
            }
6164
6165 2
            $str = \mb_substr($str, 0, $length);
6166
6167 2
            $array = \explode(' ', $str);
6168 2
            \array_pop($array);
6169 2
            $new_str = \implode(' ', $array);
6170
6171 2
            if ($new_str === '') {
6172 2
                return ((string) \mb_substr($str, 0, $length - 1)) . $str_add_on;
6173
            }
6174
        } else {
6175 4
            if ((int) self::strlen($str, $encoding) <= $length) {
6176
                return $str;
6177
            }
6178
6179 4
            if (self::substr($str, $length - 1, 1, $encoding) === ' ') {
6180 3
                return ((string) self::substr($str, 0, $length - 1, $encoding)) . $str_add_on;
6181
            }
6182
6183
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
6184 1
            $str = self::substr($str, 0, $length, $encoding);
6185
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
6186 1
            if ($str === false) {
6187
                return '' . $str_add_on;
6188
            }
6189
6190 1
            $array = \explode(' ', $str);
6191 1
            \array_pop($array);
6192 1
            $new_str = \implode(' ', $array);
6193
6194 1
            if ($new_str === '') {
6195
                return ((string) self::substr($str, 0, $length - 1, $encoding)) . $str_add_on;
6196
            }
6197
        }
6198
6199 3
        return $new_str . $str_add_on;
6200
    }
6201
6202
    /**
6203
     * Returns the longest common prefix between the $str1 and $str2.
6204
     *
6205
     * @param string $str1     <p>The input sting.</p>
6206
     * @param string $str2     <p>Second string for comparison.</p>
6207
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6208
     *
6209
     * @return string
6210
     */
6211 10
    public static function str_longest_common_prefix(
6212
        string $str1,
6213
        string $str2,
6214
        string $encoding = 'UTF-8'
6215
    ): string {
6216
        // init
6217 10
        $longest_common_prefix = '';
6218
6219 10
        if ($encoding === 'UTF-8') {
6220 5
            $max_length = (int) \min(
6221 5
                \mb_strlen($str1),
6222 5
                \mb_strlen($str2)
6223
            );
6224
6225 5
            for ($i = 0; $i < $max_length; ++$i) {
6226 4
                $char = \mb_substr($str1, $i, 1);
6227
6228
                if (
6229 4
                    $char !== false
6230
                    &&
6231 4
                    $char === \mb_substr($str2, $i, 1)
6232
                ) {
6233 3
                    $longest_common_prefix .= $char;
6234
                } else {
6235 3
                    break;
6236
                }
6237
            }
6238
        } else {
6239 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
6240
6241 5
            $max_length = (int) \min(
6242 5
                self::strlen($str1, $encoding),
6243 5
                self::strlen($str2, $encoding)
6244
            );
6245
6246 5
            for ($i = 0; $i < $max_length; ++$i) {
6247 4
                $char = self::substr($str1, $i, 1, $encoding);
6248
6249
                if (
6250 4
                    $char !== false
6251
                    &&
6252 4
                    $char === self::substr($str2, $i, 1, $encoding)
6253
                ) {
6254 3
                    $longest_common_prefix .= $char;
6255
                } else {
6256 3
                    break;
6257
                }
6258
            }
6259
        }
6260
6261 10
        return $longest_common_prefix;
6262
    }
6263
6264
    /**
6265
     * Returns the longest common substring between the $str1 and $str2.
6266
     * In the case of ties, it returns that which occurs first.
6267
     *
6268
     * @param string $str1
6269
     * @param string $str2     <p>Second string for comparison.</p>
6270
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6271
     *
6272
     * @return string string with its $str being the longest common substring
6273
     */
6274 11
    public static function str_longest_common_substring(
6275
        string $str1,
6276
        string $str2,
6277
        string $encoding = 'UTF-8'
6278
    ): string {
6279 11
        if ($str1 === '' || $str2 === '') {
6280 2
            return '';
6281
        }
6282
6283
        // Uses dynamic programming to solve
6284
        // http://en.wikipedia.org/wiki/Longest_common_substring_problem
6285
6286 9
        if ($encoding === 'UTF-8') {
6287 4
            $str_length = (int) \mb_strlen($str1);
6288 4
            $other_length = (int) \mb_strlen($str2);
6289
        } else {
6290 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
6291
6292 5
            $str_length = (int) self::strlen($str1, $encoding);
6293 5
            $other_length = (int) self::strlen($str2, $encoding);
6294
        }
6295
6296
        // Return if either string is empty
6297 9
        if ($str_length === 0 || $other_length === 0) {
6298
            return '';
6299
        }
6300
6301 9
        $len = 0;
6302 9
        $end = 0;
6303 9
        $table = \array_fill(
6304 9
            0,
6305 9
            $str_length + 1,
6306 9
            \array_fill(0, $other_length + 1, 0)
6307
        );
6308
6309 9
        if ($encoding === 'UTF-8') {
6310 9
            for ($i = 1; $i <= $str_length; ++$i) {
6311 9
                for ($j = 1; $j <= $other_length; ++$j) {
6312 9
                    $str_char = \mb_substr($str1, $i - 1, 1);
6313 9
                    $other_char = \mb_substr($str2, $j - 1, 1);
6314
6315 9
                    if ($str_char === $other_char) {
6316 8
                        $table[$i][$j] = $table[$i - 1][$j - 1] + 1;
6317 8
                        if ($table[$i][$j] > $len) {
6318 8
                            $len = $table[$i][$j];
6319 8
                            $end = $i;
6320
                        }
6321
                    } else {
6322 9
                        $table[$i][$j] = 0;
6323
                    }
6324
                }
6325
            }
6326
        } else {
6327
            for ($i = 1; $i <= $str_length; ++$i) {
6328
                for ($j = 1; $j <= $other_length; ++$j) {
6329
                    $str_char = self::substr($str1, $i - 1, 1, $encoding);
6330
                    $other_char = self::substr($str2, $j - 1, 1, $encoding);
6331
6332
                    if ($str_char === $other_char) {
6333
                        $table[$i][$j] = $table[$i - 1][$j - 1] + 1;
6334
                        if ($table[$i][$j] > $len) {
6335
                            $len = $table[$i][$j];
6336
                            $end = $i;
6337
                        }
6338
                    } else {
6339
                        $table[$i][$j] = 0;
6340
                    }
6341
                }
6342
            }
6343
        }
6344
6345 9
        if ($encoding === 'UTF-8') {
6346 9
            return (string) \mb_substr($str1, $end - $len, $len);
6347
        }
6348
6349
        return (string) self::substr($str1, $end - $len, $len, $encoding);
6350
    }
6351
6352
    /**
6353
     * Returns the longest common suffix between the $str1 and $str2.
6354
     *
6355
     * @param string $str1
6356
     * @param string $str2     <p>Second string for comparison.</p>
6357
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6358
     *
6359
     * @return string
6360
     */
6361 10
    public static function str_longest_common_suffix(
6362
        string $str1,
6363
        string $str2,
6364
        string $encoding = 'UTF-8'
6365
    ): string {
6366 10
        if ($str1 === '' || $str2 === '') {
6367 2
            return '';
6368
        }
6369
6370 8
        if ($encoding === 'UTF-8') {
6371 4
            $max_length = (int) \min(
6372 4
                \mb_strlen($str1, $encoding),
6373 4
                \mb_strlen($str2, $encoding)
6374
            );
6375
6376 4
            $longest_common_suffix = '';
6377 4
            for ($i = 1; $i <= $max_length; ++$i) {
6378 4
                $char = \mb_substr($str1, -$i, 1);
6379
6380
                if (
6381 4
                    $char !== false
6382
                    &&
6383 4
                    $char === \mb_substr($str2, -$i, 1)
6384
                ) {
6385 3
                    $longest_common_suffix = $char . $longest_common_suffix;
6386
                } else {
6387 3
                    break;
6388
                }
6389
            }
6390
        } else {
6391 4
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
6392
6393 4
            $max_length = (int) \min(
6394 4
                self::strlen($str1, $encoding),
6395 4
                self::strlen($str2, $encoding)
6396
            );
6397
6398 4
            $longest_common_suffix = '';
6399 4
            for ($i = 1; $i <= $max_length; ++$i) {
6400 4
                $char = self::substr($str1, -$i, 1, $encoding);
6401
6402
                if (
6403 4
                    $char !== false
6404
                    &&
6405 4
                    $char === self::substr($str2, -$i, 1, $encoding)
6406
                ) {
6407 3
                    $longest_common_suffix = $char . $longest_common_suffix;
6408
                } else {
6409 3
                    break;
6410
                }
6411
            }
6412
        }
6413
6414 8
        return $longest_common_suffix;
6415
    }
6416
6417
    /**
6418
     * Returns true if $str matches the supplied pattern, false otherwise.
6419
     *
6420
     * @param string $str     <p>The input string.</p>
6421
     * @param string $pattern <p>Regex pattern to match against.</p>
6422
     *
6423
     * @return bool whether or not $str matches the pattern
6424
     */
6425
    public static function str_matches_pattern(string $str, string $pattern): bool
6426
    {
6427
        return (bool) \preg_match('/' . $pattern . '/u', $str);
6428
    }
6429
6430
    /**
6431
     * Returns whether or not a character exists at an index. Offsets may be
6432
     * negative to count from the last character in the string. Implements
6433
     * part of the ArrayAccess interface.
6434
     *
6435
     * @param string $str      <p>The input string.</p>
6436
     * @param int    $offset   <p>The index to check.</p>
6437
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6438
     *
6439
     * @return bool whether or not the index exists
6440
     */
6441 6
    public static function str_offset_exists(string $str, int $offset, string $encoding = 'UTF-8'): bool
6442
    {
6443
        // init
6444 6
        $length = (int) self::strlen($str, $encoding);
6445
6446 6
        if ($offset >= 0) {
6447 3
            return $length > $offset;
6448
        }
6449
6450 3
        return $length >= \abs($offset);
6451
    }
6452
6453
    /**
6454
     * Returns the character at the given index. Offsets may be negative to
6455
     * count from the last character in the string. Implements part of the
6456
     * ArrayAccess interface, and throws an OutOfBoundsException if the index
6457
     * does not exist.
6458
     *
6459
     * @param string $str      <p>The input string.</p>
6460
     * @param int    $index    <p>The <strong>index</strong> from which to retrieve the char.</p>
6461
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6462
     *
6463
     * @throws \OutOfBoundsException if the positive or negative offset does not exist
6464
     *
6465
     * @return string the character at the specified index
6466
     */
6467 2
    public static function str_offset_get(string $str, int $index, string $encoding = 'UTF-8'): string
6468
    {
6469
        // init
6470 2
        $length = (int) self::strlen($str);
6471
6472
        if (
6473 2
            ($index >= 0 && $length <= $index)
6474
            ||
6475 2
            $length < \abs($index)
6476
        ) {
6477 1
            throw new \OutOfBoundsException('No character exists at the index');
6478
        }
6479
6480 1
        return self::char_at($str, $index, $encoding);
6481
    }
6482
6483
    /**
6484
     * Pad a UTF-8 string to a given length with another string.
6485
     *
6486
     * @param string     $str        <p>The input string.</p>
6487
     * @param int        $pad_length <p>The length of return string.</p>
6488
     * @param string     $pad_string [optional] <p>String to use for padding the input string.</p>
6489
     * @param int|string $pad_type   [optional] <p>
6490
     *                               Can be <strong>STR_PAD_RIGHT</strong> (default), [or string "right"]<br>
6491
     *                               <strong>STR_PAD_LEFT</strong> [or string "left"] or<br>
6492
     *                               <strong>STR_PAD_BOTH</strong> [or string "both"]
6493
     *                               </p>
6494
     * @param string     $encoding   [optional] <p>Default: 'UTF-8'</p>
6495
     *
6496
     * @return string returns the padded string
6497
     */
6498 41
    public static function str_pad(
6499
        string $str,
6500
        int $pad_length,
6501
        string $pad_string = ' ',
6502
        $pad_type = \STR_PAD_RIGHT,
6503
        string $encoding = 'UTF-8'
6504
    ): string {
6505 41
        if ($pad_length === 0 || $pad_string === '') {
6506 1
            return $str;
6507
        }
6508
6509 41
        if ($pad_type !== (int) $pad_type) {
6510 13
            if ($pad_type === 'left') {
6511 3
                $pad_type = \STR_PAD_LEFT;
6512 10
            } elseif ($pad_type === 'right') {
6513 6
                $pad_type = \STR_PAD_RIGHT;
6514 4
            } elseif ($pad_type === 'both') {
6515 3
                $pad_type = \STR_PAD_BOTH;
6516
            } else {
6517 1
                throw new \InvalidArgumentException(
6518 1
                    'Pad expects $pad_type to be "STR_PAD_*" or ' . "to be one of 'left', 'right' or 'both'"
6519
                );
6520
            }
6521
        }
6522
6523 40
        if ($encoding === 'UTF-8') {
6524 25
            $str_length = (int) \mb_strlen($str);
6525
6526 25
            if ($pad_length >= $str_length) {
6527
                switch ($pad_type) {
6528 25
                    case \STR_PAD_LEFT:
6529 8
                        $ps_length = (int) \mb_strlen($pad_string);
6530
6531 8
                        $diff = ($pad_length - $str_length);
6532
6533 8
                        $pre = (string) \mb_substr(
6534 8
                            \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
6535 8
                            0,
6536 8
                            $diff
6537
                        );
6538 8
                        $post = '';
6539
6540 8
                        break;
6541
6542 20
                    case \STR_PAD_BOTH:
6543 14
                        $diff = ($pad_length - $str_length);
6544
6545 14
                        $ps_length_left = (int) \floor($diff / 2);
6546
6547 14
                        $ps_length_right = (int) \ceil($diff / 2);
6548
6549 14
                        $pre = (string) \mb_substr(
6550 14
                            \str_repeat($pad_string, $ps_length_left),
6551 14
                            0,
6552 14
                            $ps_length_left
6553
                        );
6554 14
                        $post = (string) \mb_substr(
6555 14
                            \str_repeat($pad_string, $ps_length_right),
6556 14
                            0,
6557 14
                            $ps_length_right
6558
                        );
6559
6560 14
                        break;
6561
6562 9
                    case \STR_PAD_RIGHT:
6563
                    default:
6564 9
                        $ps_length = (int) \mb_strlen($pad_string);
6565
6566 9
                        $diff = ($pad_length - $str_length);
6567
6568 9
                        $post = (string) \mb_substr(
6569 9
                            \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
6570 9
                            0,
6571 9
                            $diff
6572
                        );
6573 9
                        $pre = '';
6574
                }
6575
6576 25
                return $pre . $str . $post;
6577
            }
6578
6579 3
            return $str;
6580
        }
6581
6582 15
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
6583
6584 15
        $str_length = (int) self::strlen($str, $encoding);
6585
6586 15
        if ($pad_length >= $str_length) {
6587
            switch ($pad_type) {
6588 14
                case \STR_PAD_LEFT:
6589 5
                    $ps_length = (int) self::strlen($pad_string, $encoding);
6590
6591 5
                    $diff = ($pad_length - $str_length);
6592
6593 5
                    $pre = (string) self::substr(
6594 5
                        \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
6595 5
                        0,
6596 5
                        $diff,
6597 5
                        $encoding
6598
                    );
6599 5
                    $post = '';
6600
6601 5
                    break;
6602
6603 9
                case \STR_PAD_BOTH:
6604 3
                    $diff = ($pad_length - $str_length);
6605
6606 3
                    $ps_length_left = (int) \floor($diff / 2);
6607
6608 3
                    $ps_length_right = (int) \ceil($diff / 2);
6609
6610 3
                    $pre = (string) self::substr(
6611 3
                        \str_repeat($pad_string, $ps_length_left),
6612 3
                        0,
6613 3
                        $ps_length_left,
6614 3
                        $encoding
6615
                    );
6616 3
                    $post = (string) self::substr(
6617 3
                        \str_repeat($pad_string, $ps_length_right),
6618 3
                        0,
6619 3
                        $ps_length_right,
6620 3
                        $encoding
6621
                    );
6622
6623 3
                    break;
6624
6625 6
                case \STR_PAD_RIGHT:
6626
                default:
6627 6
                    $ps_length = (int) self::strlen($pad_string, $encoding);
6628
6629 6
                    $diff = ($pad_length - $str_length);
6630
6631 6
                    $post = (string) self::substr(
6632 6
                        \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
6633 6
                        0,
6634 6
                        $diff,
6635 6
                        $encoding
6636
                    );
6637 6
                    $pre = '';
6638
            }
6639
6640 14
            return $pre . $str . $post;
6641
        }
6642
6643 1
        return $str;
6644
    }
6645
6646
    /**
6647
     * Returns a new string of a given length such that both sides of the
6648
     * string are padded. Alias for "UTF8::str_pad()" with a $pad_type of 'both'.
6649
     *
6650
     * @param string $str
6651
     * @param int    $length   <p>Desired string length after padding.</p>
6652
     * @param string $pad_str  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
6653
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6654
     *
6655
     * @return string
6656
     *                <p>The string with padding applied.</p>
6657
     */
6658 11
    public static function str_pad_both(
6659
        string $str,
6660
        int $length,
6661
        string $pad_str = ' ',
6662
        string $encoding = 'UTF-8'
6663
    ): string {
6664 11
        return self::str_pad(
6665 11
            $str,
6666 11
            $length,
6667 11
            $pad_str,
6668 11
            \STR_PAD_BOTH,
6669 11
            $encoding
6670
        );
6671
    }
6672
6673
    /**
6674
     * Returns a new string of a given length such that the beginning of the
6675
     * string is padded. Alias for "UTF8::str_pad()" with a $pad_type of 'left'.
6676
     *
6677
     * @param string $str
6678
     * @param int    $length   <p>Desired string length after padding.</p>
6679
     * @param string $pad_str  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
6680
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6681
     *
6682
     * @return string
6683
     *                <p>The string with left padding.</p>
6684
     */
6685 7
    public static function str_pad_left(
6686
        string $str,
6687
        int $length,
6688
        string $pad_str = ' ',
6689
        string $encoding = 'UTF-8'
6690
    ): string {
6691 7
        return self::str_pad(
6692 7
            $str,
6693 7
            $length,
6694 7
            $pad_str,
6695 7
            \STR_PAD_LEFT,
6696 7
            $encoding
6697
        );
6698
    }
6699
6700
    /**
6701
     * Returns a new string of a given length such that the end of the string
6702
     * is padded. Alias for "UTF8::str_pad()" with a $pad_type of 'right'.
6703
     *
6704
     * @param string $str
6705
     * @param int    $length   <p>Desired string length after padding.</p>
6706
     * @param string $pad_str  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
6707
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6708
     *
6709
     * @return string
6710
     *                <p>The string with right padding.</p>
6711
     */
6712 7
    public static function str_pad_right(
6713
        string $str,
6714
        int $length,
6715
        string $pad_str = ' ',
6716
        string $encoding = 'UTF-8'
6717
    ): string {
6718 7
        return self::str_pad(
6719 7
            $str,
6720 7
            $length,
6721 7
            $pad_str,
6722 7
            \STR_PAD_RIGHT,
6723 7
            $encoding
6724
        );
6725
    }
6726
6727
    /**
6728
     * Repeat a string.
6729
     *
6730
     * @param string $str        <p>
6731
     *                           The string to be repeated.
6732
     *                           </p>
6733
     * @param int    $multiplier <p>
6734
     *                           Number of time the input string should be
6735
     *                           repeated.
6736
     *                           </p>
6737
     *                           <p>
6738
     *                           multiplier has to be greater than or equal to 0.
6739
     *                           If the multiplier is set to 0, the function
6740
     *                           will return an empty string.
6741
     *                           </p>
6742
     *
6743
     * @return string
6744
     *                <p>The repeated string.</P>
6745
     */
6746 9
    public static function str_repeat(string $str, int $multiplier): string
6747
    {
6748 9
        $str = self::filter($str);
6749
6750 9
        return \str_repeat($str, $multiplier);
6751
    }
6752
6753
    /**
6754
     * INFO: This is only a wrapper for "str_replace()"  -> the original functions is already UTF-8 safe.
6755
     *
6756
     * Replace all occurrences of the search string with the replacement string
6757
     *
6758
     * @see http://php.net/manual/en/function.str-replace.php
6759
     *
6760
     * @param mixed $search  <p>
6761
     *                       The value being searched for, otherwise known as the needle.
6762
     *                       An array may be used to designate multiple needles.
6763
     *                       </p>
6764
     * @param mixed $replace <p>
6765
     *                       The replacement value that replaces found search
6766
     *                       values. An array may be used to designate multiple replacements.
6767
     *                       </p>
6768
     * @param mixed $subject <p>
6769
     *                       The string or array being searched and replaced on,
6770
     *                       otherwise known as the haystack.
6771
     *                       </p>
6772
     *                       <p>
6773
     *                       If subject is an array, then the search and
6774
     *                       replace is performed with every entry of
6775
     *                       subject, and the return value is an array as
6776
     *                       well.
6777
     *                       </p>
6778
     * @param int   $count   [optional] If passed, this will hold the number of matched and replaced needles
6779
     *
6780
     * @return mixed this function returns a string or an array with the replaced values
6781
     */
6782 12
    public static function str_replace(
6783
        $search,
6784
        $replace,
6785
        $subject,
6786
        int &$count = null
6787
    ) {
6788
        /**
6789
         * @psalm-suppress PossiblyNullArgument
6790
         */
6791 12
        return \str_replace(
6792 12
            $search,
6793 12
            $replace,
6794 12
            $subject,
6795 12
            $count
6796
        );
6797
    }
6798
6799
    /**
6800
     * Replaces $search from the beginning of string with $replacement.
6801
     *
6802
     * @param string $str         <p>The input string.</p>
6803
     * @param string $search      <p>The string to search for.</p>
6804
     * @param string $replacement <p>The replacement.</p>
6805
     *
6806
     * @return string string after the replacements
6807
     */
6808 17
    public static function str_replace_beginning(
6809
        string $str,
6810
        string $search,
6811
        string $replacement
6812
    ): string {
6813 17
        if ($str === '') {
6814 4
            if ($replacement === '') {
6815 2
                return '';
6816
            }
6817
6818 2
            if ($search === '') {
6819 2
                return $replacement;
6820
            }
6821
        }
6822
6823 13
        if ($search === '') {
6824 2
            return $str . $replacement;
6825
        }
6826
6827 11
        if (\strpos($str, $search) === 0) {
6828 9
            return $replacement . \substr($str, \strlen($search));
6829
        }
6830
6831 2
        return $str;
6832
    }
6833
6834
    /**
6835
     * Replaces $search from the ending of string with $replacement.
6836
     *
6837
     * @param string $str         <p>The input string.</p>
6838
     * @param string $search      <p>The string to search for.</p>
6839
     * @param string $replacement <p>The replacement.</p>
6840
     *
6841
     * @return string string after the replacements
6842
     */
6843 17
    public static function str_replace_ending(
6844
        string $str,
6845
        string $search,
6846
        string $replacement
6847
    ): string {
6848 17
        if ($str === '') {
6849 4
            if ($replacement === '') {
6850 2
                return '';
6851
            }
6852
6853 2
            if ($search === '') {
6854 2
                return $replacement;
6855
            }
6856
        }
6857
6858 13
        if ($search === '') {
6859 2
            return $str . $replacement;
6860
        }
6861
6862 11
        if (\strpos($str, $search, \strlen($str) - \strlen($search)) !== false) {
6863 8
            $str = \substr($str, 0, -\strlen($search)) . $replacement;
6864
        }
6865
6866 11
        return $str;
6867
    }
6868
6869
    /**
6870
     * Replace the first "$search"-term with the "$replace"-term.
6871
     *
6872
     * @param string $search
6873
     * @param string $replace
6874
     * @param string $subject
6875
     *
6876
     * @return string
6877
     *
6878
     * @psalm-suppress InvalidReturnType
6879
     */
6880 2
    public static function str_replace_first(
6881
        string $search,
6882
        string $replace,
6883
        string $subject
6884
    ): string {
6885 2
        $pos = self::strpos($subject, $search);
6886
6887 2
        if ($pos !== false) {
6888
            /**
6889
             * @psalm-suppress InvalidReturnStatement
6890
             */
6891 2
            return self::substr_replace(
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::substr_repl...)self::strlen($search)) could return the type string[] which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
6892 2
                $subject,
6893 2
                $replace,
6894 2
                $pos,
6895 2
                (int) self::strlen($search)
6896
            );
6897
        }
6898
6899 2
        return $subject;
6900
    }
6901
6902
    /**
6903
     * Replace the last "$search"-term with the "$replace"-term.
6904
     *
6905
     * @param string $search
6906
     * @param string $replace
6907
     * @param string $subject
6908
     *
6909
     * @return string
6910
     *
6911
     * @psalm-suppress InvalidReturnType
6912
     */
6913 2
    public static function str_replace_last(
6914
        string $search,
6915
        string $replace,
6916
        string $subject
6917
    ): string {
6918 2
        $pos = self::strrpos($subject, $search);
6919 2
        if ($pos !== false) {
6920
            /**
6921
             * @psalm-suppress InvalidReturnStatement
6922
             */
6923 2
            return self::substr_replace(
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::substr_repl...)self::strlen($search)) could return the type string[] which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
6924 2
                $subject,
6925 2
                $replace,
6926 2
                $pos,
6927 2
                (int) self::strlen($search)
6928
            );
6929
        }
6930
6931 2
        return $subject;
6932
    }
6933
6934
    /**
6935
     * Shuffles all the characters in the string.
6936
     *
6937
     * PS: uses random algorithm which is weak for cryptography purposes
6938
     *
6939
     * @param string $str      <p>The input string</p>
6940
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6941
     *
6942
     * @return string the shuffled string
6943
     */
6944 5
    public static function str_shuffle(string $str, string $encoding = 'UTF-8'): string
6945
    {
6946 5
        if ($encoding === 'UTF-8') {
6947 5
            $indexes = \range(0, (int) \mb_strlen($str) - 1);
6948
            /** @noinspection NonSecureShuffleUsageInspection */
6949 5
            \shuffle($indexes);
6950
6951
            // init
6952 5
            $shuffled_str = '';
6953
6954 5
            foreach ($indexes as &$i) {
6955 5
                $tmp_sub_str = \mb_substr($str, $i, 1);
6956 5
                if ($tmp_sub_str !== false) {
6957 5
                    $shuffled_str .= $tmp_sub_str;
6958
                }
6959
            }
6960
        } else {
6961
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
6962
6963
            $indexes = \range(0, (int) self::strlen($str, $encoding) - 1);
6964
            /** @noinspection NonSecureShuffleUsageInspection */
6965
            \shuffle($indexes);
6966
6967
            // init
6968
            $shuffled_str = '';
6969
6970
            foreach ($indexes as &$i) {
6971
                $tmp_sub_str = self::substr($str, $i, 1, $encoding);
6972
                if ($tmp_sub_str !== false) {
6973
                    $shuffled_str .= $tmp_sub_str;
6974
                }
6975
            }
6976
        }
6977
6978 5
        return $shuffled_str;
6979
    }
6980
6981
    /**
6982
     * Returns the substring beginning at $start, and up to, but not including
6983
     * the index specified by $end. If $end is omitted, the function extracts
6984
     * the remaining string. If $end is negative, it is computed from the end
6985
     * of the string.
6986
     *
6987
     * @param string $str
6988
     * @param int    $start    <p>Initial index from which to begin extraction.</p>
6989
     * @param int    $end      [optional] <p>Index at which to end extraction. Default: null</p>
6990
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6991
     *
6992
     * @return false|string
6993
     *                      <p>The extracted substring.</p><p>If <i>str</i> is shorter than <i>start</i>
6994
     *                      characters long, <b>FALSE</b> will be returned.
6995
     */
6996 18
    public static function str_slice(
6997
        string $str,
6998
        int $start,
6999
        int $end = null,
7000
        string $encoding = 'UTF-8'
7001
    ) {
7002 18
        if ($encoding === 'UTF-8') {
7003 7
            if ($end === null) {
7004 1
                $length = (int) \mb_strlen($str);
7005 6
            } elseif ($end >= 0 && $end <= $start) {
7006 2
                return '';
7007 4
            } elseif ($end < 0) {
7008 1
                $length = (int) \mb_strlen($str) + $end - $start;
7009
            } else {
7010 3
                $length = $end - $start;
7011
            }
7012
7013 5
            return \mb_substr($str, $start, $length);
7014
        }
7015
7016 11
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
7017
7018 11
        if ($end === null) {
7019 5
            $length = (int) self::strlen($str, $encoding);
7020 6
        } elseif ($end >= 0 && $end <= $start) {
7021 2
            return '';
7022 4
        } elseif ($end < 0) {
7023 1
            $length = (int) self::strlen($str, $encoding) + $end - $start;
7024
        } else {
7025 3
            $length = $end - $start;
7026
        }
7027
7028 9
        return self::substr($str, $start, $length, $encoding);
7029
    }
7030
7031
    /**
7032
     * Convert a string to e.g.: "snake_case"
7033
     *
7034
     * @param string $str
7035
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7036
     *
7037
     * @return string string in snake_case
7038
     */
7039 22
    public static function str_snakeize(string $str, string $encoding = 'UTF-8'): string
7040
    {
7041 22
        if ($str === '') {
7042
            return '';
7043
        }
7044
7045 22
        $str = \str_replace(
7046 22
            '-',
7047 22
            '_',
7048 22
            self::normalize_whitespace($str)
7049
        );
7050
7051 22
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
7052 19
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
7053
        }
7054
7055 22
        $str = (string) \preg_replace_callback(
7056 22
            '/([\\p{N}|\\p{Lu}])/u',
7057
            /**
7058
             * @param string[] $matches
7059
             *
7060
             * @return string
7061
             */
7062
            static function (array $matches) use ($encoding): string {
7063 9
                $match = $matches[1];
7064 9
                $match_int = (int) $match;
7065
7066 9
                if ((string) $match_int === $match) {
7067 4
                    return '_' . $match . '_';
7068
                }
7069
7070 5
                if ($encoding === 'UTF-8') {
7071 5
                    return '_' . \mb_strtolower($match);
7072
                }
7073
7074
                return '_' . self::strtolower($match, $encoding);
7075 22
            },
7076 22
            $str
7077
        );
7078
7079 22
        $str = (string) \preg_replace(
7080
            [
7081 22
                '/\\s+/u',           // convert spaces to "_"
7082
                '/^\\s+|\\s+$/u', // trim leading & trailing spaces
7083
                '/_+/',                 // remove double "_"
7084
            ],
7085
            [
7086 22
                '_',
7087
                '',
7088
                '_',
7089
            ],
7090 22
            $str
7091
        );
7092
7093 22
        return \trim(\trim($str, '_')); // trim leading & trailing "_" + whitespace
7094
    }
7095
7096
    /**
7097
     * Sort all characters according to code points.
7098
     *
7099
     * @param string $str    <p>A UTF-8 string.</p>
7100
     * @param bool   $unique <p>Sort unique. If <strong>true</strong>, repeated characters are ignored.</p>
7101
     * @param bool   $desc   <p>If <strong>true</strong>, will sort characters in reverse code point order.</p>
7102
     *
7103
     * @return string string of sorted characters
7104
     */
7105 2
    public static function str_sort(string $str, bool $unique = false, bool $desc = false): string
7106
    {
7107 2
        $array = self::codepoints($str);
7108
7109 2
        if ($unique) {
7110 2
            $array = \array_flip(\array_flip($array));
7111
        }
7112
7113 2
        if ($desc) {
7114 2
            \arsort($array);
0 ignored issues
show
Bug introduced by
It seems like $array can also be of type null; however, parameter $array of arsort() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

7114
            \arsort(/** @scrutinizer ignore-type */ $array);
Loading history...
7115
        } else {
7116 2
            \asort($array);
0 ignored issues
show
Bug introduced by
It seems like $array can also be of type null; however, parameter $array of asort() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

7116
            \asort(/** @scrutinizer ignore-type */ $array);
Loading history...
7117
        }
7118
7119 2
        return self::string($array);
7120
    }
7121
7122
    /**
7123
     * Convert a string to an array of Unicode characters.
7124
     *
7125
     * @param int|int[]|string|string[] $str                     <p>The string to split into array.</p>
7126
     * @param int                       $length                  [optional] <p>Max character length of each array
7127
     *                                                           element.</p>
7128
     * @param bool                      $clean_utf8              [optional] <p>Remove non UTF-8 chars from the string.</p>
7129
     * @param bool                      $try_to_use_mb_functions [optional] <p>Set to false, if you don't want to use
7130
     *                                                           "mb_substr"</p>
7131
     *
7132
     * @return array
7133
     *               <p>An array containing chunks of the input.</p>
7134
     */
7135 89
    public static function str_split(
7136
        $str,
7137
        int $length = 1,
7138
        bool $clean_utf8 = false,
7139
        bool $try_to_use_mb_functions = true
7140
    ): array {
7141 89
        if ($length <= 0) {
7142 3
            return [];
7143
        }
7144
7145 88
        if (\is_array($str) === true) {
7146 2
            foreach ($str as $k => &$v) {
7147 2
                $v = self::str_split(
7148 2
                    $v,
7149 2
                    $length,
7150 2
                    $clean_utf8,
7151 2
                    $try_to_use_mb_functions
7152
                );
7153
            }
7154
7155 2
            return $str;
7156
        }
7157
7158
        // init
7159 88
        $str = (string) $str;
7160
7161 88
        if ($str === '') {
7162 13
            return [];
7163
        }
7164
7165 85
        if ($clean_utf8 === true) {
7166 19
            $str = self::clean($str);
7167
        }
7168
7169
        if (
7170 85
            $try_to_use_mb_functions === true
7171
            &&
7172 85
            self::$SUPPORT['mbstring'] === true
7173
        ) {
7174 81
            $i_max = \mb_strlen($str);
7175 81
            if ($i_max <= 127) {
7176 75
                $ret = [];
7177 75
                for ($i = 0; $i < $i_max; ++$i) {
7178 75
                    $ret[] = \mb_substr($str, $i, 1);
7179
                }
7180
            } else {
7181 16
                $return_array = [];
7182 16
                \preg_match_all('/./us', $str, $return_array);
7183 81
                $ret = $return_array[0] ?? [];
7184
            }
7185 23
        } elseif (self::$SUPPORT['pcre_utf8'] === true) {
7186 17
            $return_array = [];
7187 17
            \preg_match_all('/./us', $str, $return_array);
7188 17
            $ret = $return_array[0] ?? [];
7189
        } else {
7190
7191
            // fallback
7192
7193 8
            $ret = [];
7194 8
            $len = \strlen($str);
7195
7196
            /** @noinspection ForeachInvariantsInspection */
7197 8
            for ($i = 0; $i < $len; ++$i) {
7198 8
                if (($str[$i] & "\x80") === "\x00") {
7199 8
                    $ret[] = $str[$i];
7200
                } elseif (
7201 8
                    isset($str[$i + 1])
7202
                    &&
7203 8
                    ($str[$i] & "\xE0") === "\xC0"
7204
                ) {
7205 4
                    if (($str[$i + 1] & "\xC0") === "\x80") {
7206 4
                        $ret[] = $str[$i] . $str[$i + 1];
7207
7208 4
                        ++$i;
7209
                    }
7210
                } elseif (
7211 6
                    isset($str[$i + 2])
7212
                    &&
7213 6
                    ($str[$i] & "\xF0") === "\xE0"
7214
                ) {
7215
                    if (
7216 6
                        ($str[$i + 1] & "\xC0") === "\x80"
7217
                        &&
7218 6
                        ($str[$i + 2] & "\xC0") === "\x80"
7219
                    ) {
7220 6
                        $ret[] = $str[$i] . $str[$i + 1] . $str[$i + 2];
7221
7222 6
                        $i += 2;
7223
                    }
7224
                } elseif (
7225
                    isset($str[$i + 3])
7226
                    &&
7227
                    ($str[$i] & "\xF8") === "\xF0"
7228
                ) {
7229
                    if (
7230
                        ($str[$i + 1] & "\xC0") === "\x80"
7231
                        &&
7232
                        ($str[$i + 2] & "\xC0") === "\x80"
7233
                        &&
7234
                        ($str[$i + 3] & "\xC0") === "\x80"
7235
                    ) {
7236
                        $ret[] = $str[$i] . $str[$i + 1] . $str[$i + 2] . $str[$i + 3];
7237
7238
                        $i += 3;
7239
                    }
7240
                }
7241
            }
7242
        }
7243
7244 85
        if ($length > 1) {
7245 11
            $ret = \array_chunk($ret, $length);
7246
7247 11
            return \array_map(
7248
                static function (array &$item): string {
7249 11
                    return \implode('', $item);
7250 11
                },
7251 11
                $ret
7252
            );
7253
        }
7254
7255 78
        if (isset($ret[0]) && $ret[0] === '') {
7256
            return [];
7257
        }
7258
7259 78
        return $ret;
7260
    }
7261
7262
    /**
7263
     * Splits the string with the provided regular expression, returning an
7264
     * array of Stringy objects. An optional integer $limit will truncate the
7265
     * results.
7266
     *
7267
     * @param string $str
7268
     * @param string $pattern <p>The regex with which to split the string.</p>
7269
     * @param int    $limit   [optional] <p>Maximum number of results to return. Default: -1 === no limit</p>
7270
     *
7271
     * @return string[] an array of strings
7272
     */
7273 16
    public static function str_split_pattern(string $str, string $pattern, int $limit = -1): array
7274
    {
7275 16
        if ($limit === 0) {
7276 2
            return [];
7277
        }
7278
7279 14
        if ($pattern === '') {
7280 1
            return [$str];
7281
        }
7282
7283 13
        if (self::$SUPPORT['mbstring'] === true) {
7284 13
            if ($limit >= 0) {
7285
                /** @noinspection PhpComposerExtensionStubsInspection */
7286 8
                $result_tmp = \mb_split($pattern, $str);
7287
7288 8
                $result = [];
7289 8
                foreach ($result_tmp as $item_tmp) {
7290 8
                    if ($limit === 0) {
7291 4
                        break;
7292
                    }
7293 8
                    --$limit;
7294
7295 8
                    $result[] = $item_tmp;
7296
                }
7297
7298 8
                return $result;
7299
            }
7300
7301
            /** @noinspection PhpComposerExtensionStubsInspection */
7302 5
            return \mb_split($pattern, $str);
7303
        }
7304
7305
        if ($limit > 0) {
7306
            ++$limit;
7307
        } else {
7308
            $limit = -1;
7309
        }
7310
7311
        $array = \preg_split('/' . \preg_quote($pattern, '/') . '/u', $str, $limit);
7312
7313
        if ($array === false) {
7314
            return [];
7315
        }
7316
7317
        if ($limit > 0 && \count($array) === $limit) {
7318
            \array_pop($array);
7319
        }
7320
7321
        return $array;
7322
    }
7323
7324
    /**
7325
     * Check if the string starts with the given substring.
7326
     *
7327
     * @param string $haystack <p>The string to search in.</p>
7328
     * @param string $needle   <p>The substring to search for.</p>
7329
     *
7330
     * @return bool
7331
     */
7332 19
    public static function str_starts_with(string $haystack, string $needle): bool
7333
    {
7334 19
        if ($needle === '') {
7335 2
            return true;
7336
        }
7337
7338 19
        if ($haystack === '') {
7339
            return false;
7340
        }
7341
7342 19
        return \strpos($haystack, $needle) === 0;
7343
    }
7344
7345
    /**
7346
     * Returns true if the string begins with any of $substrings, false otherwise.
7347
     *
7348
     * - case-sensitive
7349
     *
7350
     * @param string $str        <p>The input string.</p>
7351
     * @param array  $substrings <p>Substrings to look for.</p>
7352
     *
7353
     * @return bool whether or not $str starts with $substring
7354
     */
7355 8
    public static function str_starts_with_any(string $str, array $substrings): bool
7356
    {
7357 8
        if ($str === '') {
7358
            return false;
7359
        }
7360
7361 8
        if ($substrings === []) {
7362
            return false;
7363
        }
7364
7365 8
        foreach ($substrings as &$substring) {
7366 8
            if (self::str_starts_with($str, $substring)) {
7367 8
                return true;
7368
            }
7369
        }
7370
7371 6
        return false;
7372
    }
7373
7374
    /**
7375
     * Gets the substring after the first occurrence of a separator.
7376
     *
7377
     * @param string $str       <p>The input string.</p>
7378
     * @param string $separator <p>The string separator.</p>
7379
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
7380
     *
7381
     * @return string
7382
     */
7383 1
    public static function str_substr_after_first_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
7384
    {
7385 1
        if ($separator === '' || $str === '') {
7386 1
            return '';
7387
        }
7388
7389 1
        if ($encoding === 'UTF-8') {
7390 1
            $offset = \mb_strpos($str, $separator);
7391 1
            if ($offset === false) {
7392 1
                return '';
7393
            }
7394
7395 1
            return (string) \mb_substr(
7396 1
                $str,
7397 1
                $offset + (int) \mb_strlen($separator)
7398
            );
7399
        }
7400
7401
        $offset = self::strpos($str, $separator, 0, $encoding);
7402
        if ($offset === false) {
7403
            return '';
7404
        }
7405
7406
        return (string) \mb_substr(
7407
            $str,
7408
            $offset + (int) self::strlen($separator, $encoding),
7409
            null,
7410
            $encoding
7411
        );
7412
    }
7413
7414
    /**
7415
     * Gets the substring after the last occurrence of a separator.
7416
     *
7417
     * @param string $str       <p>The input string.</p>
7418
     * @param string $separator <p>The string separator.</p>
7419
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
7420
     *
7421
     * @return string
7422
     */
7423 1
    public static function str_substr_after_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
7424
    {
7425 1
        if ($separator === '' || $str === '') {
7426 1
            return '';
7427
        }
7428
7429 1
        if ($encoding === 'UTF-8') {
7430 1
            $offset = \mb_strrpos($str, $separator);
7431 1
            if ($offset === false) {
7432 1
                return '';
7433
            }
7434
7435 1
            return (string) \mb_substr(
7436 1
                $str,
7437 1
                $offset + (int) \mb_strlen($separator)
7438
            );
7439
        }
7440
7441
        $offset = self::strrpos($str, $separator, 0, $encoding);
7442
        if ($offset === false) {
7443
            return '';
7444
        }
7445
7446
        return (string) self::substr(
7447
            $str,
7448
            $offset + (int) self::strlen($separator, $encoding),
7449
            null,
7450
            $encoding
7451
        );
7452
    }
7453
7454
    /**
7455
     * Gets the substring before the first occurrence of a separator.
7456
     *
7457
     * @param string $str       <p>The input string.</p>
7458
     * @param string $separator <p>The string separator.</p>
7459
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
7460
     *
7461
     * @return string
7462
     */
7463 1
    public static function str_substr_before_first_separator(
7464
        string $str,
7465
        string $separator,
7466
        string $encoding = 'UTF-8'
7467
    ): string {
7468 1
        if ($separator === '' || $str === '') {
7469 1
            return '';
7470
        }
7471
7472 1
        if ($encoding === 'UTF-8') {
7473 1
            $offset = \mb_strpos($str, $separator);
7474 1
            if ($offset === false) {
7475 1
                return '';
7476
            }
7477
7478 1
            return (string) \mb_substr(
7479 1
                $str,
7480 1
                0,
7481 1
                $offset
7482
            );
7483
        }
7484
7485
        $offset = self::strpos($str, $separator, 0, $encoding);
7486
        if ($offset === false) {
7487
            return '';
7488
        }
7489
7490
        return (string) self::substr(
7491
            $str,
7492
            0,
7493
            $offset,
7494
            $encoding
7495
        );
7496
    }
7497
7498
    /**
7499
     * Gets the substring before the last occurrence of a separator.
7500
     *
7501
     * @param string $str       <p>The input string.</p>
7502
     * @param string $separator <p>The string separator.</p>
7503
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
7504
     *
7505
     * @return string
7506
     */
7507 1
    public static function str_substr_before_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
7508
    {
7509 1
        if ($separator === '' || $str === '') {
7510 1
            return '';
7511
        }
7512
7513 1
        if ($encoding === 'UTF-8') {
7514 1
            $offset = \mb_strrpos($str, $separator);
7515 1
            if ($offset === false) {
7516 1
                return '';
7517
            }
7518
7519 1
            return (string) \mb_substr(
7520 1
                $str,
7521 1
                0,
7522 1
                $offset
7523
            );
7524
        }
7525
7526
        $offset = self::strrpos($str, $separator, 0, $encoding);
7527
        if ($offset === false) {
7528
            return '';
7529
        }
7530
7531
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
7532
7533
        return (string) self::substr(
7534
            $str,
7535
            0,
7536
            $offset,
7537
            $encoding
7538
        );
7539
    }
7540
7541
    /**
7542
     * Gets the substring after (or before via "$before_needle") the first occurrence of the "$needle".
7543
     *
7544
     * @param string $str           <p>The input string.</p>
7545
     * @param string $needle        <p>The string to look for.</p>
7546
     * @param bool   $before_needle [optional] <p>Default: false</p>
7547
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
7548
     *
7549
     * @return string
7550
     */
7551 2
    public static function str_substr_first(
7552
        string $str,
7553
        string $needle,
7554
        bool $before_needle = false,
7555
        string $encoding = 'UTF-8'
7556
    ): string {
7557 2
        if ($str === '' || $needle === '') {
7558 2
            return '';
7559
        }
7560
7561 2
        if ($encoding === 'UTF-8') {
7562 2
            if ($before_needle === true) {
7563 1
                $part = \mb_strstr(
7564 1
                    $str,
7565 1
                    $needle,
7566 1
                    $before_needle
7567
                );
7568
            } else {
7569 1
                $part = \mb_strstr(
7570 1
                    $str,
7571 2
                    $needle
7572
                );
7573
            }
7574
        } else {
7575
            $part = self::strstr(
7576
                $str,
7577
                $needle,
7578
                $before_needle,
7579
                $encoding
7580
            );
7581
        }
7582
7583 2
        return $part === false ? '' : $part;
7584
    }
7585
7586
    /**
7587
     * Gets the substring after (or before via "$before_needle") the last occurrence of the "$needle".
7588
     *
7589
     * @param string $str           <p>The input string.</p>
7590
     * @param string $needle        <p>The string to look for.</p>
7591
     * @param bool   $before_needle [optional] <p>Default: false</p>
7592
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
7593
     *
7594
     * @return string
7595
     */
7596 2
    public static function str_substr_last(
7597
        string $str,
7598
        string $needle,
7599
        bool $before_needle = false,
7600
        string $encoding = 'UTF-8'
7601
    ): string {
7602 2
        if ($str === '' || $needle === '') {
7603 2
            return '';
7604
        }
7605
7606 2
        if ($encoding === 'UTF-8') {
7607 2
            if ($before_needle === true) {
7608 1
                $part = \mb_strrchr(
7609 1
                    $str,
7610 1
                    $needle,
7611 1
                    $before_needle
7612
                );
7613
            } else {
7614 1
                $part = \mb_strrchr(
7615 1
                    $str,
7616 2
                    $needle
7617
                );
7618
            }
7619
        } else {
7620
            $part = self::strrchr(
7621
                $str,
7622
                $needle,
7623
                $before_needle,
7624
                $encoding
7625
            );
7626
        }
7627
7628 2
        return $part === false ? '' : $part;
7629
    }
7630
7631
    /**
7632
     * Surrounds $str with the given substring.
7633
     *
7634
     * @param string $str
7635
     * @param string $substring <p>The substring to add to both sides.</P>
7636
     *
7637
     * @return string string with the substring both prepended and appended
7638
     */
7639 5
    public static function str_surround(string $str, string $substring): string
7640
    {
7641 5
        return $substring . $str . $substring;
7642
    }
7643
7644
    /**
7645
     * Returns a trimmed string with the first letter of each word capitalized.
7646
     * Also accepts an array, $ignore, allowing you to list words not to be
7647
     * capitalized.
7648
     *
7649
     * @param string              $str
7650
     * @param array|string[]|null $ignore                        [optional] <p>An array of words not to capitalize or null.
7651
     *                                                           Default: null</p>
7652
     * @param string              $encoding                      [optional] <p>Default: 'UTF-8'</p>
7653
     * @param bool                $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
7654
     * @param string|null         $lang                          [optional] <p>Set the language for special cases: az, el, lt,
7655
     *                                                           tr</p>
7656
     * @param bool                $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ ->
7657
     *                                                           ß</p>
7658
     * @param bool                $use_trim_first                [optional] <p>true === trim the input string, first</p>
7659
     * @param string|null         $word_define_chars             [optional] <p>An string of chars that will be used as whitespace separator === words.</p>
7660
     *
7661
     * @return string
7662
     *                <p>The titleized string.</p>
7663
     */
7664 10
    public static function str_titleize(
7665
        string $str,
7666
        array $ignore = null,
7667
        string $encoding = 'UTF-8',
7668
        bool $clean_utf8 = false,
7669
        string $lang = null,
7670
        bool $try_to_keep_the_string_length = false,
7671
        bool $use_trim_first = true,
7672
        string $word_define_chars = null
7673
    ): string {
7674 10
        if ($str === '') {
7675
            return '';
7676
        }
7677
7678 10
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
7679 9
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
7680
        }
7681
7682 10
        if ($use_trim_first === true) {
7683 10
            $str = \trim($str);
7684
        }
7685
7686 10
        if ($clean_utf8 === true) {
7687
            $str = self::clean($str);
7688
        }
7689
7690 10
        $use_mb_functions = $lang === null && $try_to_keep_the_string_length === false;
7691
7692 10
        if ($word_define_chars) {
7693 4
            $word_define_chars = \preg_quote($word_define_chars, '/');
7694
        } else {
7695 6
            $word_define_chars = '';
7696
        }
7697
7698 10
        $str = (string) \preg_replace_callback(
7699 10
            '/([^\\s' . $word_define_chars . ']+)/u',
7700
            static function (array $match) use ($try_to_keep_the_string_length, $lang, $ignore, $use_mb_functions, $encoding): string {
7701 10
                if ($ignore !== null && \in_array($match[0], $ignore, true)) {
7702 4
                    return $match[0];
7703
                }
7704
7705 10
                if ($use_mb_functions === true) {
7706 10
                    if ($encoding === 'UTF-8') {
7707 10
                        return \mb_strtoupper(\mb_substr($match[0], 0, 1))
7708 10
                               . \mb_strtolower(\mb_substr($match[0], 1));
7709
                    }
7710
7711
                    return \mb_strtoupper(\mb_substr($match[0], 0, 1, $encoding), $encoding)
7712
                           . \mb_strtolower(\mb_substr($match[0], 1, null, $encoding), $encoding);
7713
                }
7714
7715
                return self::ucfirst(
7716
                    self::strtolower(
7717
                        $match[0],
7718
                        $encoding,
7719
                        false,
7720
                        $lang,
7721
                        $try_to_keep_the_string_length
7722
                    ),
7723
                    $encoding,
7724
                    false,
7725
                    $lang,
7726
                    $try_to_keep_the_string_length
7727
                );
7728 10
            },
7729 10
            $str
7730
        );
7731
7732 10
        return $str;
7733
    }
7734
7735
    /**
7736
     * Returns a trimmed string in proper title case.
7737
     *
7738
     * Also accepts an array, $ignore, allowing you to list words not to be
7739
     * capitalized.
7740
     *
7741
     * Adapted from John Gruber's script.
7742
     *
7743
     * @see https://gist.github.com/gruber/9f9e8650d68b13ce4d78
7744
     *
7745
     * @param string $str
7746
     * @param array  $ignore   <p>An array of words not to capitalize.</p>
7747
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7748
     *
7749
     * @return string the titleized string
7750
     */
7751 35
    public static function str_titleize_for_humans(
7752
        string $str,
7753
        array $ignore = [],
7754
        string $encoding = 'UTF-8'
7755
    ): string {
7756 35
        $small_words = \array_merge(
7757
            [
7758 35
                '(?<!q&)a',
7759
                'an',
7760
                'and',
7761
                'as',
7762
                'at(?!&t)',
7763
                'but',
7764
                'by',
7765
                'en',
7766
                'for',
7767
                'if',
7768
                'in',
7769
                'of',
7770
                'on',
7771
                'or',
7772
                'the',
7773
                'to',
7774
                'v[.]?',
7775
                'via',
7776
                'vs[.]?',
7777
            ],
7778 35
            $ignore
7779
        );
7780
7781 35
        $small_words_rx = \implode('|', $small_words);
7782 35
        $apostrophe_rx = '(?x: [\'’] [[:lower:]]* )?';
7783
7784 35
        $str = \trim($str);
7785
7786 35
        if (self::has_lowercase($str) === false) {
7787 2
            $str = self::strtolower($str, $encoding);
7788
        }
7789
7790
        // the main substitutions
7791 35
        $str = (string) \preg_replace_callback(
7792
            '~\\b (_*) (?:                                                         # 1. Leading underscore and
7793
                        ( (?<=[ ][/\\\\]) [[:alpha:]]+ [-_[:alpha:]/\\\\]+ |              # 2. file path or 
7794 35
                          [-_[:alpha:]]+ [@.:] [-_[:alpha:]@.:/]+ ' . $apostrophe_rx . ' ) #    URL, domain, or email
7795
                        |
7796 35
                        ( (?i: ' . $small_words_rx . ' ) ' . $apostrophe_rx . ' )            # 3. or small word (case-insensitive)
7797
                        |
7798 35
                        ( [[:alpha:]] [[:lower:]\'’()\[\]{}]* ' . $apostrophe_rx . ' )     # 4. or word w/o internal caps
7799
                        |
7800 35
                        ( [[:alpha:]] [[:alpha:]\'’()\[\]{}]* ' . $apostrophe_rx . ' )     # 5. or some other word
7801
                      ) (_*) \\b                                                          # 6. With trailing underscore
7802
                    ~ux',
7803
            /**
7804
             * @param string[] $matches
7805
             *
7806
             * @return string
7807
             */
7808
            static function (array $matches) use ($encoding): string {
7809
                // preserve leading underscore
7810 35
                $str = $matches[1];
7811 35
                if ($matches[2]) {
7812
                    // preserve URLs, domains, emails and file paths
7813 5
                    $str .= $matches[2];
7814 35
                } elseif ($matches[3]) {
7815
                    // lower-case small words
7816 25
                    $str .= self::strtolower($matches[3], $encoding);
7817 35
                } elseif ($matches[4]) {
7818
                    // capitalize word w/o internal caps
7819 34
                    $str .= static::ucfirst($matches[4], $encoding);
7820
                } else {
7821
                    // preserve other kinds of word (iPhone)
7822 7
                    $str .= $matches[5];
7823
                }
7824
                // preserve trailing underscore
7825 35
                $str .= $matches[6];
7826
7827 35
                return $str;
7828 35
            },
7829 35
            $str
7830
        );
7831
7832
        // Exceptions for small words: capitalize at start of title...
7833 35
        $str = (string) \preg_replace_callback(
7834
            '~(  \\A [[:punct:]]*            # start of title...
7835
                      |  [:.;?!][ ]+                # or of subsentence...
7836
                      |  [ ][\'"“‘(\[][ ]* )        # or of inserted subphrase...
7837 35
                      ( ' . $small_words_rx . ' ) \\b # ...followed by small word
7838
                     ~uxi',
7839
            /**
7840
             * @param string[] $matches
7841
             *
7842
             * @return string
7843
             */
7844
            static function (array $matches) use ($encoding): string {
7845 11
                return $matches[1] . static::ucfirst($matches[2], $encoding);
7846 35
            },
7847 35
            $str
7848
        );
7849
7850
        // ...and end of title
7851 35
        $str = (string) \preg_replace_callback(
7852 35
            '~\\b ( ' . $small_words_rx . ' ) # small word...
7853
                      (?= [[:punct:]]* \Z          # ...at the end of the title...
7854
                      |   [\'"’”)\]] [ ] )         # ...or of an inserted subphrase?
7855
                     ~uxi',
7856
            /**
7857
             * @param string[] $matches
7858
             *
7859
             * @return string
7860
             */
7861
            static function (array $matches) use ($encoding): string {
7862 3
                return static::ucfirst($matches[1], $encoding);
7863 35
            },
7864 35
            $str
7865
        );
7866
7867
        // Exceptions for small words in hyphenated compound words.
7868
        // e.g. "in-flight" -> In-Flight
7869 35
        $str = (string) \preg_replace_callback(
7870
            '~\\b
7871
                        (?<! -)                   # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (in-flight)
7872 35
                        ( ' . $small_words_rx . ' )
7873
                        (?= -[[:alpha:]]+)        # lookahead for "-someword"
7874
                       ~uxi',
7875
            /**
7876
             * @param string[] $matches
7877
             *
7878
             * @return string
7879
             */
7880
            static function (array $matches) use ($encoding): string {
7881
                return static::ucfirst($matches[1], $encoding);
7882 35
            },
7883 35
            $str
7884
        );
7885
7886
        // e.g. "Stand-in" -> "Stand-In" (Stand is already capped at this point)
7887 35
        $str = (string) \preg_replace_callback(
7888
            '~\\b
7889
                      (?<!…)                    # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (stand-in)
7890
                      ( [[:alpha:]]+- )         # $1 = first word and hyphen, should already be properly capped
7891 35
                      ( ' . $small_words_rx . ' ) # ...followed by small word
7892
                      (?!	- )                 # Negative lookahead for another -
7893
                     ~uxi',
7894
            /**
7895
             * @param string[] $matches
7896
             *
7897
             * @return string
7898
             */
7899
            static function (array $matches) use ($encoding): string {
7900
                return $matches[1] . static::ucfirst($matches[2], $encoding);
7901 35
            },
7902 35
            $str
7903
        );
7904
7905 35
        return $str;
7906
    }
7907
7908
    /**
7909
     * Get a binary representation of a specific string.
7910
     *
7911
     * @param string $str <p>The input string.</p>
7912
     *
7913
     * @return false|string
7914
     *                      <p>false on error</p>
7915
     */
7916 2
    public static function str_to_binary(string $str)
7917
    {
7918
        /** @var array|false $value - needed for PhpStan (stubs error) */
7919 2
        $value = \unpack('H*', $str);
7920 2
        if ($value === false) {
7921
            return false;
7922
        }
7923
7924
        /** @noinspection OffsetOperationsInspection */
7925 2
        return \base_convert($value[1], 16, 2);
7926
    }
7927
7928
    /**
7929
     * @param string   $str
7930
     * @param bool     $remove_empty_values <p>Remove empty values.</p>
7931
     * @param int|null $remove_short_values <p>The min. string length or null to disable</p>
7932
     *
7933
     * @return string[]
7934
     */
7935 17
    public static function str_to_lines(string $str, bool $remove_empty_values = false, int $remove_short_values = null): array
7936
    {
7937 17
        if ($str === '') {
7938 1
            return $remove_empty_values === true ? [] : [''];
7939
        }
7940
7941 16
        if (self::$SUPPORT['mbstring'] === true) {
7942
            /** @noinspection PhpComposerExtensionStubsInspection */
7943 16
            $return = \mb_split("[\r\n]{1,2}", $str);
7944
        } else {
7945
            $return = \preg_split("/[\r\n]{1,2}/u", $str);
7946
        }
7947
7948 16
        if ($return === false) {
7949
            return $remove_empty_values === true ? [] : [''];
7950
        }
7951
7952
        if (
7953 16
            $remove_short_values === null
7954
            &&
7955 16
            $remove_empty_values === false
7956
        ) {
7957 16
            return $return;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $return returns an array which contains values of type array which are incompatible with the documented value type string.
Loading history...
7958
        }
7959
7960
        return self::reduce_string_array(
7961
            $return,
7962
            $remove_empty_values,
7963
            $remove_short_values
7964
        );
7965
    }
7966
7967
    /**
7968
     * Convert a string into an array of words.
7969
     *
7970
     * @param string   $str
7971
     * @param string   $char_list           <p>Additional chars for the definition of "words".</p>
7972
     * @param bool     $remove_empty_values <p>Remove empty values.</p>
7973
     * @param int|null $remove_short_values <p>The min. string length or null to disable</p>
7974
     *
7975
     * @return string[]
7976
     */
7977 13
    public static function str_to_words(
7978
        string $str,
7979
        string $char_list = '',
7980
        bool $remove_empty_values = false,
7981
        int $remove_short_values = null
7982
    ): array {
7983 13
        if ($str === '') {
7984 4
            return $remove_empty_values === true ? [] : [''];
7985
        }
7986
7987 13
        $char_list = self::rxClass($char_list, '\pL');
7988
7989 13
        $return = \preg_split("/({$char_list}+(?:[\p{Pd}’']{$char_list}+)*)/u", $str, -1, \PREG_SPLIT_DELIM_CAPTURE);
7990 13
        if ($return === false) {
7991
            return $remove_empty_values === true ? [] : [''];
7992
        }
7993
7994
        if (
7995 13
            $remove_short_values === null
7996
            &&
7997 13
            $remove_empty_values === false
7998
        ) {
7999 13
            return $return;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $return returns an array which contains values of type array which are incompatible with the documented value type string.
Loading history...
8000
        }
8001
8002 2
        $tmp_return = self::reduce_string_array(
8003 2
            $return,
8004 2
            $remove_empty_values,
8005 2
            $remove_short_values
8006
        );
8007
8008 2
        foreach ($tmp_return as &$item) {
8009 2
            $item = (string) $item;
8010
        }
8011
8012 2
        return $tmp_return;
8013
    }
8014
8015
    /**
8016
     * alias for "UTF8::to_ascii()"
8017
     *
8018
     * @param string $str
8019
     * @param string $unknown
8020
     * @param bool   $strict
8021
     *
8022
     * @return string
8023
     *
8024
     * @see UTF8::to_ascii()
8025
     * @deprecated <p>please use "UTF8::to_ascii()"</p>
8026
     */
8027 7
    public static function str_transliterate(
8028
        string $str,
8029
        string $unknown = '?',
8030
        bool $strict = false
8031
    ): string {
8032 7
        return self::to_ascii($str, $unknown, $strict);
8033
    }
8034
8035
    /**
8036
     * Truncates the string to a given length. If $substring is provided, and
8037
     * truncating occurs, the string is further truncated so that the substring
8038
     * may be appended without exceeding the desired length.
8039
     *
8040
     * @param string $str
8041
     * @param int    $length    <p>Desired length of the truncated string.</p>
8042
     * @param string $substring [optional] <p>The substring to append if it can fit. Default: ''</p>
8043
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
8044
     *
8045
     * @return string string after truncating
8046
     */
8047 22
    public static function str_truncate(
8048
        string $str,
8049
        int $length,
8050
        string $substring = '',
8051
        string $encoding = 'UTF-8'
8052
    ): string {
8053 22
        if ($str === '') {
8054
            return '';
8055
        }
8056
8057 22
        if ($encoding === 'UTF-8') {
8058 10
            if ($length >= (int) \mb_strlen($str)) {
8059 2
                return $str;
8060
            }
8061
8062 8
            if ($substring !== '') {
8063 4
                $length -= (int) \mb_strlen($substring);
8064
8065
                /** @noinspection UnnecessaryCastingInspection */
8066 4
                return (string) \mb_substr($str, 0, $length) . $substring;
8067
            }
8068
8069
            /** @noinspection UnnecessaryCastingInspection */
8070 4
            return (string) \mb_substr($str, 0, $length);
8071
        }
8072
8073 12
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
8074
8075 12
        if ($length >= (int) self::strlen($str, $encoding)) {
8076 2
            return $str;
8077
        }
8078
8079 10
        if ($substring !== '') {
8080 6
            $length -= (int) self::strlen($substring, $encoding);
8081
        }
8082
8083
        return (
8084 10
               (string) self::substr(
8085 10
                   $str,
8086 10
                   0,
8087 10
                   $length,
8088 10
                   $encoding
8089
               )
8090 10
               ) . $substring;
8091
    }
8092
8093
    /**
8094
     * Truncates the string to a given length, while ensuring that it does not
8095
     * split words. If $substring is provided, and truncating occurs, the
8096
     * string is further truncated so that the substring may be appended without
8097
     * exceeding the desired length.
8098
     *
8099
     * @param string $str
8100
     * @param int    $length                                 <p>Desired length of the truncated string.</p>
8101
     * @param string $substring                              [optional] <p>The substring to append if it can fit. Default:
8102
     *                                                       ''</p>
8103
     * @param string $encoding                               [optional] <p>Default: 'UTF-8'</p>
8104
     * @param bool   $ignore_do_not_split_words_for_one_word [optional] <p>Default: false</p>
8105
     *
8106
     * @return string string after truncating
8107
     */
8108 47
    public static function str_truncate_safe(
8109
        string $str,
8110
        int $length,
8111
        string $substring = '',
8112
        string $encoding = 'UTF-8',
8113
        bool $ignore_do_not_split_words_for_one_word = false
8114
    ): string {
8115 47
        if ($str === '' || $length <= 0) {
8116 1
            return $substring;
8117
        }
8118
8119 47
        if ($encoding === 'UTF-8') {
8120 21
            if ($length >= (int) \mb_strlen($str)) {
8121 5
                return $str;
8122
            }
8123
8124
            // need to further trim the string so we can append the substring
8125 17
            $length -= (int) \mb_strlen($substring);
8126 17
            if ($length <= 0) {
8127 1
                return $substring;
8128
            }
8129
8130
            /** @var string|false $truncated - needed for PhpStan (stubs error) */
8131 17
            $truncated = \mb_substr($str, 0, $length);
8132 17
            if ($truncated === false) {
8133
                return '';
8134
            }
8135
8136
            // if the last word was truncated
8137 17
            $space_position = \mb_strpos($str, ' ', $length - 1);
8138 17
            if ($space_position !== $length) {
8139
                // find pos of the last occurrence of a space, get up to that
8140 13
                $last_position = \mb_strrpos($truncated, ' ', 0);
8141
8142
                if (
8143 13
                    $last_position !== false
8144
                    ||
8145 13
                    ($space_position !== false && $ignore_do_not_split_words_for_one_word === false)
8146
                ) {
8147 17
                    $truncated = (string) \mb_substr($truncated, 0, (int) $last_position);
8148
                }
8149
            }
8150
        } else {
8151 26
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8152
8153 26
            if ($length >= (int) self::strlen($str, $encoding)) {
8154 4
                return $str;
8155
            }
8156
8157
            // need to further trim the string so we can append the substring
8158 22
            $length -= (int) self::strlen($substring, $encoding);
8159 22
            if ($length <= 0) {
8160
                return $substring;
8161
            }
8162
8163 22
            $truncated = self::substr($str, 0, $length, $encoding);
8164
8165 22
            if ($truncated === false) {
8166
                return '';
8167
            }
8168
8169
            // if the last word was truncated
8170 22
            $space_position = self::strpos($str, ' ', $length - 1, $encoding);
8171 22
            if ($space_position !== $length) {
8172
                // find pos of the last occurrence of a space, get up to that
8173 12
                $last_position = self::strrpos($truncated, ' ', 0, $encoding);
8174
8175
                if (
8176 12
                    $last_position !== false
8177
                    ||
8178 12
                    ($space_position !== false && $ignore_do_not_split_words_for_one_word === false)
8179
                ) {
8180 9
                    $truncated = (string) self::substr($truncated, 0, (int) $last_position, $encoding);
8181
                }
8182
            }
8183
        }
8184
8185 39
        return $truncated . $substring;
8186
    }
8187
8188
    /**
8189
     * Returns a lowercase and trimmed string separated by underscores.
8190
     * Underscores are inserted before uppercase characters (with the exception
8191
     * of the first character of the string), and in place of spaces as well as
8192
     * dashes.
8193
     *
8194
     * @param string $str
8195
     *
8196
     * @return string the underscored string
8197
     */
8198 16
    public static function str_underscored(string $str): string
8199
    {
8200 16
        return self::str_delimit($str, '_');
8201
    }
8202
8203
    /**
8204
     * Returns an UpperCamelCase version of the supplied string. It trims
8205
     * surrounding spaces, capitalizes letters following digits, spaces, dashes
8206
     * and underscores, and removes spaces, dashes, underscores.
8207
     *
8208
     * @param string      $str                           <p>The input string.</p>
8209
     * @param string      $encoding                      [optional] <p>Default: 'UTF-8'</p>
8210
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
8211
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt, tr</p>
8212
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
8213
     *
8214
     * @return string string in UpperCamelCase
8215
     */
8216 13
    public static function str_upper_camelize(
8217
        string $str,
8218
        string $encoding = 'UTF-8',
8219
        bool $clean_utf8 = false,
8220
        string $lang = null,
8221
        bool $try_to_keep_the_string_length = false
8222
    ): string {
8223 13
        return self::ucfirst(self::str_camelize($str, $encoding), $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
8224
    }
8225
8226
    /**
8227
     * alias for "UTF8::ucfirst()"
8228
     *
8229
     * @param string      $str
8230
     * @param string      $encoding
8231
     * @param bool        $clean_utf8
8232
     * @param string|null $lang
8233
     * @param bool        $try_to_keep_the_string_length
8234
     *
8235
     * @return string
8236
     *
8237
     * @see UTF8::ucfirst()
8238
     * @deprecated <p>please use "UTF8::ucfirst()"</p>
8239
     */
8240 5
    public static function str_upper_first(
8241
        string $str,
8242
        string $encoding = 'UTF-8',
8243
        bool $clean_utf8 = false,
8244
        string $lang = null,
8245
        bool $try_to_keep_the_string_length = false
8246
    ): string {
8247 5
        return self::ucfirst(
8248 5
            $str,
8249 5
            $encoding,
8250 5
            $clean_utf8,
8251 5
            $lang,
8252 5
            $try_to_keep_the_string_length
8253
        );
8254
    }
8255
8256
    /**
8257
     * Get the number of words in a specific string.
8258
     *
8259
     * @param string $str       <p>The input string.</p>
8260
     * @param int    $format    [optional] <p>
8261
     *                          <strong>0</strong> => return a number of words (default)<br>
8262
     *                          <strong>1</strong> => return an array of words<br>
8263
     *                          <strong>2</strong> => return an array of words with word-offset as key
8264
     *                          </p>
8265
     * @param string $char_list [optional] <p>Additional chars that contains to words and do not start a new word.</p>
8266
     *
8267
     * @return int|string[] The number of words in the string
8268
     */
8269 2
    public static function str_word_count(string $str, int $format = 0, string $char_list = '')
8270
    {
8271 2
        $str_parts = self::str_to_words($str, $char_list);
8272
8273 2
        $len = \count($str_parts);
8274
8275 2
        if ($format === 1) {
8276 2
            $number_of_words = [];
8277 2
            for ($i = 1; $i < $len; $i += 2) {
8278 2
                $number_of_words[] = $str_parts[$i];
8279
            }
8280 2
        } elseif ($format === 2) {
8281 2
            $number_of_words = [];
8282 2
            $offset = (int) self::strlen($str_parts[0]);
8283 2
            for ($i = 1; $i < $len; $i += 2) {
8284 2
                $number_of_words[$offset] = $str_parts[$i];
8285 2
                $offset += (int) self::strlen($str_parts[$i]) + (int) self::strlen($str_parts[$i + 1]);
8286
            }
8287
        } else {
8288 2
            $number_of_words = (int) (($len - 1) / 2);
8289
        }
8290
8291 2
        return $number_of_words;
8292
    }
8293
8294
    /**
8295
     * Case-insensitive string comparison.
8296
     *
8297
     * INFO: Case-insensitive version of UTF8::strcmp()
8298
     *
8299
     * @param string $str1     <p>The first string.</p>
8300
     * @param string $str2     <p>The second string.</p>
8301
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
8302
     *
8303
     * @return int
8304
     *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
8305
     *             <strong>&gt; 0</strong> if str1 is greater than str2,<br>
8306
     *             <strong>0</strong> if they are equal
8307
     */
8308 23
    public static function strcasecmp(
8309
        string $str1,
8310
        string $str2,
8311
        string $encoding = 'UTF-8'
8312
    ): int {
8313 23
        return self::strcmp(
8314 23
            self::strtocasefold(
8315 23
                $str1,
8316 23
                true,
8317 23
                false,
8318 23
                $encoding,
8319 23
                null,
8320 23
                false
8321
            ),
8322 23
            self::strtocasefold(
8323 23
                $str2,
8324 23
                true,
8325 23
                false,
8326 23
                $encoding,
8327 23
                null,
8328 23
                false
8329
            )
8330
        );
8331
    }
8332
8333
    /**
8334
     * alias for "UTF8::strstr()"
8335
     *
8336
     * @param string $haystack
8337
     * @param string $needle
8338
     * @param bool   $before_needle
8339
     * @param string $encoding
8340
     * @param bool   $clean_utf8
8341
     *
8342
     * @return false|string
8343
     *
8344
     * @see UTF8::strstr()
8345
     * @deprecated <p>please use "UTF8::strstr()"</p>
8346
     */
8347 2
    public static function strchr(
8348
        string $haystack,
8349
        string $needle,
8350
        bool $before_needle = false,
8351
        string $encoding = 'UTF-8',
8352
        bool $clean_utf8 = false
8353
    ) {
8354 2
        return self::strstr(
8355 2
            $haystack,
8356 2
            $needle,
8357 2
            $before_needle,
8358 2
            $encoding,
8359 2
            $clean_utf8
8360
        );
8361
    }
8362
8363
    /**
8364
     * Case-sensitive string comparison.
8365
     *
8366
     * @param string $str1 <p>The first string.</p>
8367
     * @param string $str2 <p>The second string.</p>
8368
     *
8369
     * @return int
8370
     *             <strong>&lt; 0</strong> if str1 is less than str2<br>
8371
     *             <strong>&gt; 0</strong> if str1 is greater than str2<br>
8372
     *             <strong>0</strong> if they are equal
8373
     */
8374 29
    public static function strcmp(string $str1, string $str2): int
8375
    {
8376 29
        if ($str1 === $str2) {
8377 21
            return 0;
8378
        }
8379
8380 24
        return \strcmp(
8381 24
            \Normalizer::normalize($str1, \Normalizer::NFD),
8382 24
            \Normalizer::normalize($str2, \Normalizer::NFD)
8383
        );
8384
    }
8385
8386
    /**
8387
     * Find length of initial segment not matching mask.
8388
     *
8389
     * @param string $str
8390
     * @param string $char_list
8391
     * @param int    $offset
8392
     * @param int    $length
8393
     * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
8394
     *
8395
     * @return int
8396
     */
8397 12
    public static function strcspn(
8398
        string $str,
8399
        string $char_list,
8400
        int $offset = null,
8401
        int $length = null,
8402
        string $encoding = 'UTF-8'
8403
    ): int {
8404 12
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8405
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8406
        }
8407
8408 12
        if ($char_list === '') {
8409 2
            return (int) self::strlen($str, $encoding);
8410
        }
8411
8412 11
        if ($offset !== null || $length !== null) {
8413 3
            if ($encoding === 'UTF-8') {
8414 3
                if ($length === null) {
8415
                    /** @noinspection UnnecessaryCastingInspection */
8416 2
                    $str_tmp = \mb_substr($str, (int) $offset);
8417
                } else {
8418
                    /** @noinspection UnnecessaryCastingInspection */
8419 3
                    $str_tmp = \mb_substr($str, (int) $offset, $length);
8420
                }
8421
            } else {
8422
                /** @noinspection UnnecessaryCastingInspection */
8423
                $str_tmp = self::substr($str, (int) $offset, $length, $encoding);
8424
            }
8425
8426 3
            if ($str_tmp === false) {
8427
                return 0;
8428
            }
8429
8430
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
8431 3
            $str = $str_tmp;
8432
        }
8433
8434 11
        if ($str === '') {
8435 2
            return 0;
8436
        }
8437
8438 10
        $matches = [];
8439 10
        if (\preg_match('/^(.*?)' . self::rxClass($char_list) . '/us', $str, $matches)) {
8440 9
            $return = self::strlen($matches[1], $encoding);
8441 9
            if ($return === false) {
8442
                return 0;
8443
            }
8444
8445 9
            return $return;
8446
        }
8447
8448 2
        return (int) self::strlen($str, $encoding);
8449
    }
8450
8451
    /**
8452
     * alias for "UTF8::stristr()"
8453
     *
8454
     * @param string $haystack
8455
     * @param string $needle
8456
     * @param bool   $before_needle
8457
     * @param string $encoding
8458
     * @param bool   $clean_utf8
8459
     *
8460
     * @return false|string
8461
     *
8462
     * @see UTF8::stristr()
8463
     * @deprecated <p>please use "UTF8::stristr()"</p>
8464
     */
8465 1
    public static function strichr(
8466
        string $haystack,
8467
        string $needle,
8468
        bool $before_needle = false,
8469
        string $encoding = 'UTF-8',
8470
        bool $clean_utf8 = false
8471
    ) {
8472 1
        return self::stristr(
8473 1
            $haystack,
8474 1
            $needle,
8475 1
            $before_needle,
8476 1
            $encoding,
8477 1
            $clean_utf8
8478
        );
8479
    }
8480
8481
    /**
8482
     * Create a UTF-8 string from code points.
8483
     *
8484
     * INFO: opposite to UTF8::codepoints()
8485
     *
8486
     * @param array $array <p>Integer or Hexadecimal codepoints.</p>
8487
     *
8488
     * @return string UTF-8 encoded string
8489
     */
8490 4
    public static function string(array $array): string
8491
    {
8492 4
        return \implode(
8493 4
            '',
8494 4
            \array_map(
8495
                [
8496 4
                    self::class,
8497
                    'chr',
8498
                ],
8499 4
                $array
8500
            )
8501
        );
8502
    }
8503
8504
    /**
8505
     * Checks if string starts with "BOM" (Byte Order Mark Character) character.
8506
     *
8507
     * @param string $str <p>The input string.</p>
8508
     *
8509
     * @return bool
8510
     *              <strong>true</strong> if the string has BOM at the start,<br>
8511
     *              <strong>false</strong> otherwise
8512
     */
8513 6
    public static function string_has_bom(string $str): bool
8514
    {
8515
        /** @noinspection PhpUnusedLocalVariableInspection */
8516 6
        foreach (self::$BOM as $bom_string => &$bom_byte_length) {
8517 6
            if (\strpos($str, $bom_string) === 0) {
8518 6
                return true;
8519
            }
8520
        }
8521
8522 6
        return false;
8523
    }
8524
8525
    /**
8526
     * Strip HTML and PHP tags from a string + clean invalid UTF-8.
8527
     *
8528
     * @see http://php.net/manual/en/function.strip-tags.php
8529
     *
8530
     * @param string $str            <p>
8531
     *                               The input string.
8532
     *                               </p>
8533
     * @param string $allowable_tags [optional] <p>
8534
     *                               You can use the optional second parameter to specify tags which should
8535
     *                               not be stripped.
8536
     *                               </p>
8537
     *                               <p>
8538
     *                               HTML comments and PHP tags are also stripped. This is hardcoded and
8539
     *                               can not be changed with allowable_tags.
8540
     *                               </p>
8541
     * @param bool   $clean_utf8     [optional] <p>Remove non UTF-8 chars from the string.</p>
8542
     *
8543
     * @return string
8544
     *                <p>The stripped string.</p>
8545
     */
8546 4
    public static function strip_tags(
8547
        string $str,
8548
        string $allowable_tags = null,
8549
        bool $clean_utf8 = false
8550
    ): string {
8551 4
        if ($str === '') {
8552 1
            return '';
8553
        }
8554
8555 4
        if ($clean_utf8 === true) {
8556 2
            $str = self::clean($str);
8557
        }
8558
8559 4
        if ($allowable_tags === null) {
8560 4
            return \strip_tags($str);
8561
        }
8562
8563 2
        return \strip_tags($str, $allowable_tags);
8564
    }
8565
8566
    /**
8567
     * Strip all whitespace characters. This includes tabs and newline
8568
     * characters, as well as multibyte whitespace such as the thin space
8569
     * and ideographic space.
8570
     *
8571
     * @param string $str
8572
     *
8573
     * @return string
8574
     */
8575 36
    public static function strip_whitespace(string $str): string
8576
    {
8577 36
        if ($str === '') {
8578 3
            return '';
8579
        }
8580
8581 33
        return (string) \preg_replace('/[[:space:]]+/u', '', $str);
8582
    }
8583
8584
    /**
8585
     * Find the position of the first occurrence of a substring in a string, case-insensitive.
8586
     *
8587
     * @see http://php.net/manual/en/function.mb-stripos.php
8588
     *
8589
     * @param string $haystack   <p>The string from which to get the position of the first occurrence of needle.</p>
8590
     * @param string $needle     <p>The string to find in haystack.</p>
8591
     * @param int    $offset     [optional] <p>The position in haystack to start searching.</p>
8592
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
8593
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
8594
     *
8595
     * @return false|int
8596
     *                   Return the <strong>(int)</strong> numeric position of the first occurrence of needle in the
8597
     *                   haystack string,<br> or <strong>false</strong> if needle is not found
8598
     */
8599 24
    public static function stripos(
8600
        string $haystack,
8601
        string $needle,
8602
        int $offset = 0,
8603
        $encoding = 'UTF-8',
8604
        bool $clean_utf8 = false
8605
    ) {
8606 24
        if ($haystack === '' || $needle === '') {
8607 5
            return false;
8608
        }
8609
8610 23
        if ($clean_utf8 === true) {
8611
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
8612
            // if invalid characters are found in $haystack before $needle
8613 1
            $haystack = self::clean($haystack);
8614 1
            $needle = self::clean($needle);
8615
        }
8616
8617 23
        if (self::$SUPPORT['mbstring'] === true) {
8618 23
            if ($encoding === 'UTF-8') {
8619 23
                return \mb_stripos($haystack, $needle, $offset);
8620
            }
8621
8622 3
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8623
8624 3
            return \mb_stripos($haystack, $needle, $offset, $encoding);
8625
        }
8626
8627 2
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
8628
8629
        if (
8630 2
            $encoding === 'UTF-8' // INFO: "grapheme_stripos()" can't handle other encodings
8631
            &&
8632 2
            $offset >= 0 // grapheme_stripos() can't handle negative offset
8633
            &&
8634 2
            self::$SUPPORT['intl'] === true
8635
        ) {
8636
            $return_tmp = \grapheme_stripos($haystack, $needle, $offset);
8637
            if ($return_tmp !== false) {
8638
                return $return_tmp;
8639
            }
8640
        }
8641
8642
        //
8643
        // fallback for ascii only
8644
        //
8645
8646 2
        if (ASCII::is_ascii($haystack . $needle)) {
8647
            return \stripos($haystack, $needle, $offset);
8648
        }
8649
8650
        //
8651
        // fallback via vanilla php
8652
        //
8653
8654 2
        $haystack = self::strtocasefold($haystack, true, false, $encoding, null, false);
8655 2
        $needle = self::strtocasefold($needle, true, false, $encoding, null, false);
8656
8657 2
        return self::strpos($haystack, $needle, $offset, $encoding);
8658
    }
8659
8660
    /**
8661
     * Returns all of haystack starting from and including the first occurrence of needle to the end.
8662
     *
8663
     * @param string $haystack      <p>The input string. Must be valid UTF-8.</p>
8664
     * @param string $needle        <p>The string to look for. Must be valid UTF-8.</p>
8665
     * @param bool   $before_needle [optional] <p>
8666
     *                              If <b>TRUE</b>, it returns the part of the
8667
     *                              haystack before the first occurrence of the needle (excluding the needle).
8668
     *                              </p>
8669
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
8670
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
8671
     *
8672
     * @return false|string
8673
     *                      <p>A sub-string,<br>or <strong>false</strong> if needle is not found.</p>
8674
     */
8675 12
    public static function stristr(
8676
        string $haystack,
8677
        string $needle,
8678
        bool $before_needle = false,
8679
        string $encoding = 'UTF-8',
8680
        bool $clean_utf8 = false
8681
    ) {
8682 12
        if ($haystack === '' || $needle === '') {
8683 3
            return false;
8684
        }
8685
8686 9
        if ($clean_utf8 === true) {
8687
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
8688
            // if invalid characters are found in $haystack before $needle
8689 1
            $needle = self::clean($needle);
8690 1
            $haystack = self::clean($haystack);
8691
        }
8692
8693 9
        if (!$needle) {
8694
            return $haystack;
8695
        }
8696
8697 9
        if (self::$SUPPORT['mbstring'] === true) {
8698 9
            if ($encoding === 'UTF-8') {
8699 9
                return \mb_stristr($haystack, $needle, $before_needle);
8700
            }
8701
8702 1
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8703
8704 1
            return \mb_stristr($haystack, $needle, $before_needle, $encoding);
8705
        }
8706
8707
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
8708
8709
        if (
8710
            $encoding !== 'UTF-8'
8711
            &&
8712
            self::$SUPPORT['mbstring'] === false
8713
        ) {
8714
            \trigger_error('UTF8::stristr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
8715
        }
8716
8717
        if (
8718
            $encoding === 'UTF-8' // INFO: "grapheme_stristr()" can't handle other encodings
8719
            &&
8720
            self::$SUPPORT['intl'] === true
8721
        ) {
8722
            $return_tmp = \grapheme_stristr($haystack, $needle, $before_needle);
8723
            if ($return_tmp !== false) {
8724
                return $return_tmp;
8725
            }
8726
        }
8727
8728
        if (ASCII::is_ascii($needle . $haystack)) {
8729
            return \stristr($haystack, $needle, $before_needle);
8730
        }
8731
8732
        \preg_match('/^(.*?)' . \preg_quote($needle, '/') . '/usi', $haystack, $match);
8733
8734
        if (!isset($match[1])) {
8735
            return false;
8736
        }
8737
8738
        if ($before_needle) {
8739
            return $match[1];
8740
        }
8741
8742
        return self::substr($haystack, (int) self::strlen($match[1], $encoding), null, $encoding);
8743
    }
8744
8745
    /**
8746
     * Get the string length, not the byte-length!
8747
     *
8748
     * @see http://php.net/manual/en/function.mb-strlen.php
8749
     *
8750
     * @param string $str        <p>The string being checked for length.</p>
8751
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
8752
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
8753
     *
8754
     * @return false|int
8755
     *                   <p>
8756
     *                   The number <strong>(int)</strong> of characters in the string $str having character encoding
8757
     *                   $encoding.
8758
     *                   (One multi-byte character counted as +1).
8759
     *                   <br>
8760
     *                   Can return <strong>false</strong>, if e.g. mbstring is not installed and we process invalid
8761
     *                   chars.
8762
     *                   </p>
8763
     */
8764 173
    public static function strlen(
8765
        string $str,
8766
        string $encoding = 'UTF-8',
8767
        bool $clean_utf8 = false
8768
    ) {
8769 173
        if ($str === '') {
8770 21
            return 0;
8771
        }
8772
8773 171
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8774 12
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8775
        }
8776
8777 171
        if ($clean_utf8 === true) {
8778
            // "mb_strlen" and "\iconv_strlen" returns wrong length,
8779
            // if invalid characters are found in $str
8780 4
            $str = self::clean($str);
8781
        }
8782
8783
        //
8784
        // fallback via mbstring
8785
        //
8786
8787 171
        if (self::$SUPPORT['mbstring'] === true) {
8788 165
            if ($encoding === 'UTF-8') {
8789 165
                return \mb_strlen($str);
8790
            }
8791
8792 4
            return \mb_strlen($str, $encoding);
8793
        }
8794
8795
        //
8796
        // fallback for binary || ascii only
8797
        //
8798
8799
        if (
8800 8
            $encoding === 'CP850'
8801
            ||
8802 8
            $encoding === 'ASCII'
8803
        ) {
8804
            return \strlen($str);
8805
        }
8806
8807
        if (
8808 8
            $encoding !== 'UTF-8'
8809
            &&
8810 8
            self::$SUPPORT['mbstring'] === false
8811
            &&
8812 8
            self::$SUPPORT['iconv'] === false
8813
        ) {
8814 2
            \trigger_error('UTF8::strlen() without mbstring / iconv cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
8815
        }
8816
8817
        //
8818
        // fallback via iconv
8819
        //
8820
8821 8
        if (self::$SUPPORT['iconv'] === true) {
8822
            $return_tmp = \iconv_strlen($str, $encoding);
8823
            if ($return_tmp !== false) {
8824
                return $return_tmp;
8825
            }
8826
        }
8827
8828
        //
8829
        // fallback via intl
8830
        //
8831
8832
        if (
8833 8
            $encoding === 'UTF-8' // INFO: "grapheme_strlen()" can't handle other encodings
8834
            &&
8835 8
            self::$SUPPORT['intl'] === true
8836
        ) {
8837
            $return_tmp = \grapheme_strlen($str);
8838
            if ($return_tmp !== null) {
8839
                return $return_tmp;
8840
            }
8841
        }
8842
8843
        //
8844
        // fallback for ascii only
8845
        //
8846
8847 8
        if (ASCII::is_ascii($str)) {
8848 4
            return \strlen($str);
8849
        }
8850
8851
        //
8852
        // fallback via vanilla php
8853
        //
8854
8855 8
        \preg_match_all('/./us', $str, $parts);
8856
8857 8
        $return_tmp = \count($parts[0]);
8858 8
        if ($return_tmp === 0) {
8859
            return false;
8860
        }
8861
8862 8
        return $return_tmp;
8863
    }
8864
8865
    /**
8866
     * Get string length in byte.
8867
     *
8868
     * @param string $str
8869
     *
8870
     * @return int
8871
     */
8872
    public static function strlen_in_byte(string $str): int
8873
    {
8874
        if ($str === '') {
8875
            return 0;
8876
        }
8877
8878
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
8879
            // "mb_" is available if overload is used, so use it ...
8880
            return \mb_strlen($str, 'CP850'); // 8-BIT
8881
        }
8882
8883
        return \strlen($str);
8884
    }
8885
8886
    /**
8887
     * Case-insensitive string comparisons using a "natural order" algorithm.
8888
     *
8889
     * INFO: natural order version of UTF8::strcasecmp()
8890
     *
8891
     * @param string $str1     <p>The first string.</p>
8892
     * @param string $str2     <p>The second string.</p>
8893
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
8894
     *
8895
     * @return int
8896
     *             <strong>&lt; 0</strong> if str1 is less than str2<br>
8897
     *             <strong>&gt; 0</strong> if str1 is greater than str2<br>
8898
     *             <strong>0</strong> if they are equal
8899
     */
8900 2
    public static function strnatcasecmp(string $str1, string $str2, string $encoding = 'UTF-8'): int
8901
    {
8902 2
        return self::strnatcmp(
8903 2
            self::strtocasefold($str1, true, false, $encoding, null, false),
8904 2
            self::strtocasefold($str2, true, false, $encoding, null, false)
8905
        );
8906
    }
8907
8908
    /**
8909
     * String comparisons using a "natural order" algorithm
8910
     *
8911
     * INFO: natural order version of UTF8::strcmp()
8912
     *
8913
     * @see http://php.net/manual/en/function.strnatcmp.php
8914
     *
8915
     * @param string $str1 <p>The first string.</p>
8916
     * @param string $str2 <p>The second string.</p>
8917
     *
8918
     * @return int
8919
     *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
8920
     *             <strong>&gt; 0</strong> if str1 is greater than str2;<br>
8921
     *             <strong>0</strong> if they are equal
8922
     */
8923 4
    public static function strnatcmp(string $str1, string $str2): int
8924
    {
8925 4
        if ($str1 === $str2) {
8926 4
            return 0;
8927
        }
8928
8929 4
        return \strnatcmp(
8930 4
            (string) self::strtonatfold($str1),
8931 4
            (string) self::strtonatfold($str2)
8932
        );
8933
    }
8934
8935
    /**
8936
     * Case-insensitive string comparison of the first n characters.
8937
     *
8938
     * @see http://php.net/manual/en/function.strncasecmp.php
8939
     *
8940
     * @param string $str1     <p>The first string.</p>
8941
     * @param string $str2     <p>The second string.</p>
8942
     * @param int    $len      <p>The length of strings to be used in the comparison.</p>
8943
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
8944
     *
8945
     * @return int
8946
     *             <strong>&lt; 0</strong> if <i>str1</i> is less than <i>str2</i>;<br>
8947
     *             <strong>&gt; 0</strong> if <i>str1</i> is greater than <i>str2</i>;<br>
8948
     *             <strong>0</strong> if they are equal
8949
     */
8950 2
    public static function strncasecmp(
8951
        string $str1,
8952
        string $str2,
8953
        int $len,
8954
        string $encoding = 'UTF-8'
8955
    ): int {
8956 2
        return self::strncmp(
8957 2
            self::strtocasefold($str1, true, false, $encoding, null, false),
8958 2
            self::strtocasefold($str2, true, false, $encoding, null, false),
8959 2
            $len
8960
        );
8961
    }
8962
8963
    /**
8964
     * String comparison of the first n characters.
8965
     *
8966
     * @see http://php.net/manual/en/function.strncmp.php
8967
     *
8968
     * @param string $str1     <p>The first string.</p>
8969
     * @param string $str2     <p>The second string.</p>
8970
     * @param int    $len      <p>Number of characters to use in the comparison.</p>
8971
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
8972
     *
8973
     * @return int
8974
     *             <strong>&lt; 0</strong> if <i>str1</i> is less than <i>str2</i>;<br>
8975
     *             <strong>&gt; 0</strong> if <i>str1</i> is greater than <i>str2</i>;<br>
8976
     *             <strong>0</strong> if they are equal
8977
     */
8978 4
    public static function strncmp(
8979
        string $str1,
8980
        string $str2,
8981
        int $len,
8982
        string $encoding = 'UTF-8'
8983
    ): int {
8984 4
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8985
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8986
        }
8987
8988 4
        if ($encoding === 'UTF-8') {
8989 4
            $str1 = (string) \mb_substr($str1, 0, $len);
8990 4
            $str2 = (string) \mb_substr($str2, 0, $len);
8991
        } else {
8992
            $str1 = (string) self::substr($str1, 0, $len, $encoding);
8993
            $str2 = (string) self::substr($str2, 0, $len, $encoding);
8994
        }
8995
8996 4
        return self::strcmp($str1, $str2);
8997
    }
8998
8999
    /**
9000
     * Search a string for any of a set of characters.
9001
     *
9002
     * @see http://php.net/manual/en/function.strpbrk.php
9003
     *
9004
     * @param string $haystack  <p>The string where char_list is looked for.</p>
9005
     * @param string $char_list <p>This parameter is case-sensitive.</p>
9006
     *
9007
     * @return false|string string starting from the character found, or false if it is not found
9008
     */
9009 2
    public static function strpbrk(string $haystack, string $char_list)
9010
    {
9011 2
        if ($haystack === '' || $char_list === '') {
9012 2
            return false;
9013
        }
9014
9015 2
        if (\preg_match('/' . self::rxClass($char_list) . '/us', $haystack, $m)) {
9016 2
            return \substr($haystack, (int) \strpos($haystack, $m[0]));
9017
        }
9018
9019 2
        return false;
9020
    }
9021
9022
    /**
9023
     * Find the position of the first occurrence of a substring in a string.
9024
     *
9025
     * @see http://php.net/manual/en/function.mb-strpos.php
9026
     *
9027
     * @param string     $haystack   <p>The string from which to get the position of the first occurrence of needle.</p>
9028
     * @param int|string $needle     <p>The string to find in haystack.<br>Or a code point as int.</p>
9029
     * @param int        $offset     [optional] <p>The search offset. If it is not specified, 0 is used.</p>
9030
     * @param string     $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
9031
     * @param bool       $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
9032
     *
9033
     * @return false|int
9034
     *                   The <strong>(int)</strong> numeric position of the first occurrence of needle in the haystack
9035
     *                   string.<br> If needle is not found it returns false.
9036
     */
9037 53
    public static function strpos(
9038
        string $haystack,
9039
        $needle,
9040
        int $offset = 0,
9041
        $encoding = 'UTF-8',
9042
        bool $clean_utf8 = false
9043
    ) {
9044 53
        if ($haystack === '') {
9045 4
            return false;
9046
        }
9047
9048
        // iconv and mbstring do not support integer $needle
9049 52
        if ((int) $needle === $needle) {
9050
            $needle = (string) self::chr($needle);
9051
        }
9052 52
        $needle = (string) $needle;
9053
9054 52
        if ($needle === '') {
9055 2
            return false;
9056
        }
9057
9058 52
        if ($clean_utf8 === true) {
9059
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
9060
            // if invalid characters are found in $haystack before $needle
9061 3
            $needle = self::clean($needle);
9062 3
            $haystack = self::clean($haystack);
9063
        }
9064
9065 52
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9066 11
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9067
        }
9068
9069
        //
9070
        // fallback via mbstring
9071
        //
9072
9073 52
        if (self::$SUPPORT['mbstring'] === true) {
9074 50
            if ($encoding === 'UTF-8') {
9075 50
                return \mb_strpos($haystack, $needle, $offset);
9076
            }
9077
9078 2
            return \mb_strpos($haystack, $needle, $offset, $encoding);
9079
        }
9080
9081
        //
9082
        // fallback for binary || ascii only
9083
        //
9084
        if (
9085 4
            $encoding === 'CP850'
9086
            ||
9087 4
            $encoding === 'ASCII'
9088
        ) {
9089 2
            return \strpos($haystack, $needle, $offset);
9090
        }
9091
9092
        if (
9093 4
            $encoding !== 'UTF-8'
9094
            &&
9095 4
            self::$SUPPORT['iconv'] === false
9096
            &&
9097 4
            self::$SUPPORT['mbstring'] === false
9098
        ) {
9099 2
            \trigger_error('UTF8::strpos() without mbstring / iconv cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
9100
        }
9101
9102
        //
9103
        // fallback via intl
9104
        //
9105
9106
        if (
9107 4
            $encoding === 'UTF-8' // INFO: "grapheme_strpos()" can't handle other encodings
9108
            &&
9109 4
            $offset >= 0 // grapheme_strpos() can't handle negative offset
9110
            &&
9111 4
            self::$SUPPORT['intl'] === true
9112
        ) {
9113
            $return_tmp = \grapheme_strpos($haystack, $needle, $offset);
9114
            if ($return_tmp !== false) {
9115
                return $return_tmp;
9116
            }
9117
        }
9118
9119
        //
9120
        // fallback via iconv
9121
        //
9122
9123
        if (
9124 4
            $offset >= 0 // iconv_strpos() can't handle negative offset
9125
            &&
9126 4
            self::$SUPPORT['iconv'] === true
9127
        ) {
9128
            // ignore invalid negative offset to keep compatibility
9129
            // with php < 5.5.35, < 5.6.21, < 7.0.6
9130
            $return_tmp = \iconv_strpos($haystack, $needle, $offset > 0 ? $offset : 0, $encoding);
9131
            if ($return_tmp !== false) {
9132
                return $return_tmp;
9133
            }
9134
        }
9135
9136
        //
9137
        // fallback for ascii only
9138
        //
9139
9140 4
        if (ASCII::is_ascii($haystack . $needle)) {
9141 2
            return \strpos($haystack, $needle, $offset);
9142
        }
9143
9144
        //
9145
        // fallback via vanilla php
9146
        //
9147
9148 4
        $haystack_tmp = self::substr($haystack, $offset, null, $encoding);
9149 4
        if ($haystack_tmp === false) {
9150
            $haystack_tmp = '';
9151
        }
9152 4
        $haystack = (string) $haystack_tmp;
9153
9154 4
        if ($offset < 0) {
9155
            $offset = 0;
9156
        }
9157
9158 4
        $pos = \strpos($haystack, $needle);
9159 4
        if ($pos === false) {
9160 2
            return false;
9161
        }
9162
9163 4
        if ($pos) {
9164 4
            return $offset + (int) self::strlen(\substr($haystack, 0, $pos), $encoding);
9165
        }
9166
9167 2
        return $offset + 0;
9168
    }
9169
9170
    /**
9171
     * Find the position of the first occurrence of a substring in a string.
9172
     *
9173
     * @param string $haystack <p>
9174
     *                         The string being checked.
9175
     *                         </p>
9176
     * @param string $needle   <p>
9177
     *                         The position counted from the beginning of haystack.
9178
     *                         </p>
9179
     * @param int    $offset   [optional] <p>
9180
     *                         The search offset. If it is not specified, 0 is used.
9181
     *                         </p>
9182
     *
9183
     * @return false|int The numeric position of the first occurrence of needle in the
9184
     *                   haystack string. If needle is not found, it returns false.
9185
     */
9186
    public static function strpos_in_byte(string $haystack, string $needle, int $offset = 0)
9187
    {
9188
        if ($haystack === '' || $needle === '') {
9189
            return false;
9190
        }
9191
9192
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
9193
            // "mb_" is available if overload is used, so use it ...
9194
            return \mb_strpos($haystack, $needle, $offset, 'CP850'); // 8-BIT
9195
        }
9196
9197
        return \strpos($haystack, $needle, $offset);
9198
    }
9199
9200
    /**
9201
     * Find the last occurrence of a character in a string within another.
9202
     *
9203
     * @see http://php.net/manual/en/function.mb-strrchr.php
9204
     *
9205
     * @param string $haystack      <p>The string from which to get the last occurrence of needle.</p>
9206
     * @param string $needle        <p>The string to find in haystack</p>
9207
     * @param bool   $before_needle [optional] <p>
9208
     *                              Determines which portion of haystack
9209
     *                              this function returns.
9210
     *                              If set to true, it returns all of haystack
9211
     *                              from the beginning to the last occurrence of needle.
9212
     *                              If set to false, it returns all of haystack
9213
     *                              from the last occurrence of needle to the end,
9214
     *                              </p>
9215
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
9216
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
9217
     *
9218
     * @return false|string the portion of haystack or false if needle is not found
9219
     */
9220 2
    public static function strrchr(
9221
        string $haystack,
9222
        string $needle,
9223
        bool $before_needle = false,
9224
        string $encoding = 'UTF-8',
9225
        bool $clean_utf8 = false
9226
    ) {
9227 2
        if ($haystack === '' || $needle === '') {
9228 2
            return false;
9229
        }
9230
9231 2
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9232 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9233
        }
9234
9235 2
        if ($clean_utf8 === true) {
9236
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
9237
            // if invalid characters are found in $haystack before $needle
9238 2
            $needle = self::clean($needle);
9239 2
            $haystack = self::clean($haystack);
9240
        }
9241
9242
        //
9243
        // fallback via mbstring
9244
        //
9245
9246 2
        if (self::$SUPPORT['mbstring'] === true) {
9247 2
            if ($encoding === 'UTF-8') {
9248 2
                return \mb_strrchr($haystack, $needle, $before_needle);
9249
            }
9250
9251 2
            return \mb_strrchr($haystack, $needle, $before_needle, $encoding);
9252
        }
9253
9254
        //
9255
        // fallback for binary || ascii only
9256
        //
9257
9258
        if (
9259
            $before_needle === false
9260
            &&
9261
            (
9262
                $encoding === 'CP850'
9263
                ||
9264
                $encoding === 'ASCII'
9265
            )
9266
        ) {
9267
            return \strrchr($haystack, $needle);
9268
        }
9269
9270
        if (
9271
            $encoding !== 'UTF-8'
9272
            &&
9273
            self::$SUPPORT['mbstring'] === false
9274
        ) {
9275
            \trigger_error('UTF8::strrchr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
9276
        }
9277
9278
        //
9279
        // fallback via iconv
9280
        //
9281
9282
        if (self::$SUPPORT['iconv'] === true) {
9283
            $needle_tmp = self::substr($needle, 0, 1, $encoding);
9284
            if ($needle_tmp === false) {
9285
                return false;
9286
            }
9287
            $needle = (string) $needle_tmp;
9288
9289
            $pos = \iconv_strrpos($haystack, $needle, $encoding);
9290
            if ($pos === false) {
9291
                return false;
9292
            }
9293
9294
            if ($before_needle) {
9295
                return self::substr($haystack, 0, $pos, $encoding);
9296
            }
9297
9298
            return self::substr($haystack, $pos, null, $encoding);
9299
        }
9300
9301
        //
9302
        // fallback via vanilla php
9303
        //
9304
9305
        $needle_tmp = self::substr($needle, 0, 1, $encoding);
9306
        if ($needle_tmp === false) {
9307
            return false;
9308
        }
9309
        $needle = (string) $needle_tmp;
9310
9311
        $pos = self::strrpos($haystack, $needle, 0, $encoding);
9312
        if ($pos === false) {
9313
            return false;
9314
        }
9315
9316
        if ($before_needle) {
9317
            return self::substr($haystack, 0, $pos, $encoding);
9318
        }
9319
9320
        return self::substr($haystack, $pos, null, $encoding);
9321
    }
9322
9323
    /**
9324
     * Reverses characters order in the string.
9325
     *
9326
     * @param string $str      <p>The input string.</p>
9327
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
9328
     *
9329
     * @return string the string with characters in the reverse sequence
9330
     */
9331 10
    public static function strrev(string $str, string $encoding = 'UTF-8'): string
9332
    {
9333 10
        if ($str === '') {
9334 4
            return '';
9335
        }
9336
9337
        // init
9338 8
        $reversed = '';
9339
9340 8
        $str = self::emoji_encode($str, true);
9341
9342 8
        if ($encoding === 'UTF-8') {
9343 8
            if (self::$SUPPORT['intl'] === true) {
9344
                // try "grapheme" first: https://stackoverflow.com/questions/17496493/strrev-dosent-support-utf-8
9345 8
                $i = (int) \grapheme_strlen($str);
9346 8
                while ($i--) {
9347 8
                    $reversed_tmp = \grapheme_substr($str, $i, 1);
9348 8
                    if ($reversed_tmp !== false) {
9349 8
                        $reversed .= $reversed_tmp;
9350
                    }
9351
                }
9352
            } else {
9353
                $i = (int) \mb_strlen($str);
9354 8
                while ($i--) {
9355
                    $reversed_tmp = \mb_substr($str, $i, 1);
9356
                    if ($reversed_tmp !== false) {
9357
                        $reversed .= $reversed_tmp;
9358
                    }
9359
                }
9360
            }
9361
        } else {
9362
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9363
9364
            $i = (int) self::strlen($str, $encoding);
9365
            while ($i--) {
9366
                $reversed_tmp = self::substr($str, $i, 1, $encoding);
9367
                if ($reversed_tmp !== false) {
9368
                    $reversed .= $reversed_tmp;
9369
                }
9370
            }
9371
        }
9372
9373 8
        return self::emoji_decode($reversed, true);
9374
    }
9375
9376
    /**
9377
     * Find the last occurrence of a character in a string within another, case-insensitive.
9378
     *
9379
     * @see http://php.net/manual/en/function.mb-strrichr.php
9380
     *
9381
     * @param string $haystack      <p>The string from which to get the last occurrence of needle.</p>
9382
     * @param string $needle        <p>The string to find in haystack.</p>
9383
     * @param bool   $before_needle [optional] <p>
9384
     *                              Determines which portion of haystack
9385
     *                              this function returns.
9386
     *                              If set to true, it returns all of haystack
9387
     *                              from the beginning to the last occurrence of needle.
9388
     *                              If set to false, it returns all of haystack
9389
     *                              from the last occurrence of needle to the end,
9390
     *                              </p>
9391
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
9392
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
9393
     *
9394
     * @return false|string the portion of haystack or<br>false if needle is not found
9395
     */
9396 3
    public static function strrichr(
9397
        string $haystack,
9398
        string $needle,
9399
        bool $before_needle = false,
9400
        string $encoding = 'UTF-8',
9401
        bool $clean_utf8 = false
9402
    ) {
9403 3
        if ($haystack === '' || $needle === '') {
9404 2
            return false;
9405
        }
9406
9407 3
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9408 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9409
        }
9410
9411 3
        if ($clean_utf8 === true) {
9412
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
9413
            // if invalid characters are found in $haystack before $needle
9414 2
            $needle = self::clean($needle);
9415 2
            $haystack = self::clean($haystack);
9416
        }
9417
9418
        //
9419
        // fallback via mbstring
9420
        //
9421
9422 3
        if (self::$SUPPORT['mbstring'] === true) {
9423 3
            if ($encoding === 'UTF-8') {
9424 3
                return \mb_strrichr($haystack, $needle, $before_needle);
9425
            }
9426
9427 2
            return \mb_strrichr($haystack, $needle, $before_needle, $encoding);
9428
        }
9429
9430
        //
9431
        // fallback via vanilla php
9432
        //
9433
9434
        $needle_tmp = self::substr($needle, 0, 1, $encoding);
9435
        if ($needle_tmp === false) {
9436
            return false;
9437
        }
9438
        $needle = (string) $needle_tmp;
9439
9440
        $pos = self::strripos($haystack, $needle, 0, $encoding);
9441
        if ($pos === false) {
9442
            return false;
9443
        }
9444
9445
        if ($before_needle) {
9446
            return self::substr($haystack, 0, $pos, $encoding);
9447
        }
9448
9449
        return self::substr($haystack, $pos, null, $encoding);
9450
    }
9451
9452
    /**
9453
     * Find the position of the last occurrence of a substring in a string, case-insensitive.
9454
     *
9455
     * @param string     $haystack   <p>The string to look in.</p>
9456
     * @param int|string $needle     <p>The string to look for.</p>
9457
     * @param int        $offset     [optional] <p>Number of characters to ignore in the beginning or end.</p>
9458
     * @param string     $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
9459
     * @param bool       $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
9460
     *
9461
     * @return false|int
9462
     *                   <p>The <strong>(int)</strong> numeric position of the last occurrence of needle in the haystack
9463
     *                   string.<br>If needle is not found, it returns false.</p>
9464
     */
9465 3
    public static function strripos(
9466
        string $haystack,
9467
        $needle,
9468
        int $offset = 0,
9469
        string $encoding = 'UTF-8',
9470
        bool $clean_utf8 = false
9471
    ) {
9472 3
        if ($haystack === '') {
9473
            return false;
9474
        }
9475
9476
        // iconv and mbstring do not support integer $needle
9477 3
        if ((int) $needle === $needle && $needle >= 0) {
9478
            $needle = (string) self::chr($needle);
9479
        }
9480 3
        $needle = (string) $needle;
9481
9482 3
        if ($needle === '') {
9483
            return false;
9484
        }
9485
9486 3
        if ($clean_utf8 === true) {
9487
            // mb_strripos() && iconv_strripos() is not tolerant to invalid characters
9488 2
            $needle = self::clean($needle);
9489 2
            $haystack = self::clean($haystack);
9490
        }
9491
9492 3
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9493 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9494
        }
9495
9496
        //
9497
        // fallback via mbstrig
9498
        //
9499
9500 3
        if (self::$SUPPORT['mbstring'] === true) {
9501 3
            if ($encoding === 'UTF-8') {
9502 3
                return \mb_strripos($haystack, $needle, $offset);
9503
            }
9504
9505
            return \mb_strripos($haystack, $needle, $offset, $encoding);
9506
        }
9507
9508
        //
9509
        // fallback for binary || ascii only
9510
        //
9511
9512
        if (
9513
            $encoding === 'CP850'
9514
            ||
9515
            $encoding === 'ASCII'
9516
        ) {
9517
            return \strripos($haystack, $needle, $offset);
9518
        }
9519
9520
        if (
9521
            $encoding !== 'UTF-8'
9522
            &&
9523
            self::$SUPPORT['mbstring'] === false
9524
        ) {
9525
            \trigger_error('UTF8::strripos() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
9526
        }
9527
9528
        //
9529
        // fallback via intl
9530
        //
9531
9532
        if (
9533
            $encoding === 'UTF-8' // INFO: "grapheme_strripos()" can't handle other encodings
9534
            &&
9535
            $offset >= 0 // grapheme_strripos() can't handle negative offset
9536
            &&
9537
            self::$SUPPORT['intl'] === true
9538
        ) {
9539
            $return_tmp = \grapheme_strripos($haystack, $needle, $offset);
9540
            if ($return_tmp !== false) {
9541
                return $return_tmp;
9542
            }
9543
        }
9544
9545
        //
9546
        // fallback for ascii only
9547
        //
9548
9549
        if (ASCII::is_ascii($haystack . $needle)) {
9550
            return \strripos($haystack, $needle, $offset);
9551
        }
9552
9553
        //
9554
        // fallback via vanilla php
9555
        //
9556
9557
        $haystack = self::strtocasefold($haystack, true, false, $encoding);
9558
        $needle = self::strtocasefold($needle, true, false, $encoding);
9559
9560
        return self::strrpos($haystack, $needle, $offset, $encoding, $clean_utf8);
9561
    }
9562
9563
    /**
9564
     * Finds position of last occurrence of a string within another, case-insensitive.
9565
     *
9566
     * @param string $haystack <p>
9567
     *                         The string from which to get the position of the last occurrence
9568
     *                         of needle.
9569
     *                         </p>
9570
     * @param string $needle   <p>
9571
     *                         The string to find in haystack.
9572
     *                         </p>
9573
     * @param int    $offset   [optional] <p>
9574
     *                         The position in haystack
9575
     *                         to start searching.
9576
     *                         </p>
9577
     *
9578
     * @return false|int
9579
     *                   <p>eturn the numeric position of the last occurrence of needle in the
9580
     *                   haystack string, or false if needle is not found.</p>
9581
     */
9582
    public static function strripos_in_byte(string $haystack, string $needle, int $offset = 0)
9583
    {
9584
        if ($haystack === '' || $needle === '') {
9585
            return false;
9586
        }
9587
9588
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
9589
            // "mb_" is available if overload is used, so use it ...
9590
            return \mb_strripos($haystack, $needle, $offset, 'CP850'); // 8-BIT
9591
        }
9592
9593
        return \strripos($haystack, $needle, $offset);
9594
    }
9595
9596
    /**
9597
     * Find the position of the last occurrence of a substring in a string.
9598
     *
9599
     * @see http://php.net/manual/en/function.mb-strrpos.php
9600
     *
9601
     * @param string     $haystack   <p>The string being checked, for the last occurrence of needle</p>
9602
     * @param int|string $needle     <p>The string to find in haystack.<br>Or a code point as int.</p>
9603
     * @param int        $offset     [optional] <p>May be specified to begin searching an arbitrary number of characters
9604
     *                               into the string. Negative values will stop searching at an arbitrary point prior to
9605
     *                               the end of the string.
9606
     *                               </p>
9607
     * @param string     $encoding   [optional] <p>Set the charset.</p>
9608
     * @param bool       $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
9609
     *
9610
     * @return false|int
9611
     *                   <p>The <strong>(int)</strong> numeric position of the last occurrence of needle in the haystack
9612
     *                   string.<br>If needle is not found, it returns false.</p>
9613
     */
9614 35
    public static function strrpos(
9615
        string $haystack,
9616
        $needle,
9617
        int $offset = 0,
9618
        string $encoding = 'UTF-8',
9619
        bool $clean_utf8 = false
9620
    ) {
9621 35
        if ($haystack === '') {
9622 3
            return false;
9623
        }
9624
9625
        // iconv and mbstring do not support integer $needle
9626 34
        if ((int) $needle === $needle && $needle >= 0) {
9627 2
            $needle = (string) self::chr($needle);
9628
        }
9629 34
        $needle = (string) $needle;
9630
9631 34
        if ($needle === '') {
9632 2
            return false;
9633
        }
9634
9635 34
        if ($clean_utf8 === true) {
9636
            // mb_strrpos && iconv_strrpos is not tolerant to invalid characters
9637 4
            $needle = self::clean($needle);
9638 4
            $haystack = self::clean($haystack);
9639
        }
9640
9641 34
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9642 8
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9643
        }
9644
9645
        //
9646
        // fallback via mbstring
9647
        //
9648
9649 34
        if (self::$SUPPORT['mbstring'] === true) {
9650 34
            if ($encoding === 'UTF-8') {
9651 34
                return \mb_strrpos($haystack, $needle, $offset);
9652
            }
9653
9654 2
            return \mb_strrpos($haystack, $needle, $offset, $encoding);
9655
        }
9656
9657
        //
9658
        // fallback for binary || ascii only
9659
        //
9660
9661
        if (
9662
            $encoding === 'CP850'
9663
            ||
9664
            $encoding === 'ASCII'
9665
        ) {
9666
            return \strrpos($haystack, $needle, $offset);
9667
        }
9668
9669
        if (
9670
            $encoding !== 'UTF-8'
9671
            &&
9672
            self::$SUPPORT['mbstring'] === false
9673
        ) {
9674
            \trigger_error('UTF8::strrpos() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
9675
        }
9676
9677
        //
9678
        // fallback via intl
9679
        //
9680
9681
        if (
9682
            $offset >= 0 // grapheme_strrpos() can't handle negative offset
9683
            &&
9684
            $encoding === 'UTF-8' // INFO: "grapheme_strrpos()" can't handle other encodings
9685
            &&
9686
            self::$SUPPORT['intl'] === true
9687
        ) {
9688
            $return_tmp = \grapheme_strrpos($haystack, $needle, $offset);
9689
            if ($return_tmp !== false) {
9690
                return $return_tmp;
9691
            }
9692
        }
9693
9694
        //
9695
        // fallback for ascii only
9696
        //
9697
9698
        if (ASCII::is_ascii($haystack . $needle)) {
9699
            return \strrpos($haystack, $needle, $offset);
9700
        }
9701
9702
        //
9703
        // fallback via vanilla php
9704
        //
9705
9706
        $haystack_tmp = null;
9707
        if ($offset > 0) {
9708
            $haystack_tmp = self::substr($haystack, $offset);
9709
        } elseif ($offset < 0) {
9710
            $haystack_tmp = self::substr($haystack, 0, $offset);
9711
            $offset = 0;
9712
        }
9713
9714
        if ($haystack_tmp !== null) {
9715
            if ($haystack_tmp === false) {
9716
                $haystack_tmp = '';
9717
            }
9718
            $haystack = (string) $haystack_tmp;
9719
        }
9720
9721
        $pos = \strrpos($haystack, $needle);
9722
        if ($pos === false) {
9723
            return false;
9724
        }
9725
9726
        /** @var string|false $str_tmp - needed for PhpStan (stubs error) */
9727
        $str_tmp = \substr($haystack, 0, $pos);
9728
        if ($str_tmp === false) {
9729
            return false;
9730
        }
9731
9732
        return $offset + (int) self::strlen($str_tmp);
9733
    }
9734
9735
    /**
9736
     * Find the position of the last occurrence of a substring in a string.
9737
     *
9738
     * @param string $haystack <p>
9739
     *                         The string being checked, for the last occurrence
9740
     *                         of needle.
9741
     *                         </p>
9742
     * @param string $needle   <p>
9743
     *                         The string to find in haystack.
9744
     *                         </p>
9745
     * @param int    $offset   [optional] <p>May be specified to begin searching an arbitrary number of characters into
9746
     *                         the string. Negative values will stop searching at an arbitrary point
9747
     *                         prior to the end of the string.
9748
     *                         </p>
9749
     *
9750
     * @return false|int
9751
     *                   <p>The numeric position of the last occurrence of needle in the
9752
     *                   haystack string. If needle is not found, it returns false.</p>
9753
     */
9754
    public static function strrpos_in_byte(string $haystack, string $needle, int $offset = 0)
9755
    {
9756
        if ($haystack === '' || $needle === '') {
9757
            return false;
9758
        }
9759
9760
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
9761
            // "mb_" is available if overload is used, so use it ...
9762
            return \mb_strrpos($haystack, $needle, $offset, 'CP850'); // 8-BIT
9763
        }
9764
9765
        return \strrpos($haystack, $needle, $offset);
9766
    }
9767
9768
    /**
9769
     * Finds the length of the initial segment of a string consisting entirely of characters contained within a given
9770
     * mask.
9771
     *
9772
     * @param string $str      <p>The input string.</p>
9773
     * @param string $mask     <p>The mask of chars</p>
9774
     * @param int    $offset   [optional]
9775
     * @param int    $length   [optional]
9776
     * @param string $encoding [optional] <p>Set the charset.</p>
9777
     *
9778
     * @return false|int
9779
     */
9780 10
    public static function strspn(
9781
        string $str,
9782
        string $mask,
9783
        int $offset = 0,
9784
        int $length = null,
9785
        string $encoding = 'UTF-8'
9786
    ) {
9787 10
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9788
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9789
        }
9790
9791 10
        if ($offset || $length !== null) {
9792 2
            if ($encoding === 'UTF-8') {
9793 2
                if ($length === null) {
9794
                    $str = (string) \mb_substr($str, $offset);
9795
                } else {
9796 2
                    $str = (string) \mb_substr($str, $offset, $length);
9797
                }
9798
            } else {
9799
                $str = (string) self::substr($str, $offset, $length, $encoding);
9800
            }
9801
        }
9802
9803 10
        if ($str === '' || $mask === '') {
9804 2
            return 0;
9805
        }
9806
9807 8
        $matches = [];
9808
9809 8
        return \preg_match('/^' . self::rxClass($mask) . '+/u', $str, $matches) ? (int) self::strlen($matches[0], $encoding) : 0;
9810
    }
9811
9812
    /**
9813
     * Returns part of haystack string from the first occurrence of needle to the end of haystack.
9814
     *
9815
     * @param string $haystack      <p>The input string. Must be valid UTF-8.</p>
9816
     * @param string $needle        <p>The string to look for. Must be valid UTF-8.</p>
9817
     * @param bool   $before_needle [optional] <p>
9818
     *                              If <b>TRUE</b>, strstr() returns the part of the
9819
     *                              haystack before the first occurrence of the needle (excluding the needle).
9820
     *                              </p>
9821
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
9822
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
9823
     *
9824
     * @return false|string
9825
     *                      A sub-string,<br>or <strong>false</strong> if needle is not found
9826
     */
9827 3
    public static function strstr(
9828
        string $haystack,
9829
        string $needle,
9830
        bool $before_needle = false,
9831
        string $encoding = 'UTF-8',
9832
        $clean_utf8 = false
9833
    ) {
9834 3
        if ($haystack === '' || $needle === '') {
9835 2
            return false;
9836
        }
9837
9838 3
        if ($clean_utf8 === true) {
9839
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
9840
            // if invalid characters are found in $haystack before $needle
9841
            $needle = self::clean($needle);
9842
            $haystack = self::clean($haystack);
9843
        }
9844
9845 3
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9846 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9847
        }
9848
9849
        //
9850
        // fallback via mbstring
9851
        //
9852
9853 3
        if (self::$SUPPORT['mbstring'] === true) {
9854 3
            if ($encoding === 'UTF-8') {
9855 3
                return \mb_strstr($haystack, $needle, $before_needle);
9856
            }
9857
9858 2
            return \mb_strstr($haystack, $needle, $before_needle, $encoding);
9859
        }
9860
9861
        //
9862
        // fallback for binary || ascii only
9863
        //
9864
9865
        if (
9866
            $encoding === 'CP850'
9867
            ||
9868
            $encoding === 'ASCII'
9869
        ) {
9870
            return \strstr($haystack, $needle, $before_needle);
9871
        }
9872
9873
        if (
9874
            $encoding !== 'UTF-8'
9875
            &&
9876
            self::$SUPPORT['mbstring'] === false
9877
        ) {
9878
            \trigger_error('UTF8::strstr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
9879
        }
9880
9881
        //
9882
        // fallback via intl
9883
        //
9884
9885
        if (
9886
            $encoding === 'UTF-8' // INFO: "grapheme_strstr()" can't handle other encodings
9887
            &&
9888
            self::$SUPPORT['intl'] === true
9889
        ) {
9890
            $return_tmp = \grapheme_strstr($haystack, $needle, $before_needle);
9891
            if ($return_tmp !== false) {
9892
                return $return_tmp;
9893
            }
9894
        }
9895
9896
        //
9897
        // fallback for ascii only
9898
        //
9899
9900
        if (ASCII::is_ascii($haystack . $needle)) {
9901
            return \strstr($haystack, $needle, $before_needle);
9902
        }
9903
9904
        //
9905
        // fallback via vanilla php
9906
        //
9907
9908
        \preg_match('/^(.*?)' . \preg_quote($needle, '/') . '/us', $haystack, $match);
9909
9910
        if (!isset($match[1])) {
9911
            return false;
9912
        }
9913
9914
        if ($before_needle) {
9915
            return $match[1];
9916
        }
9917
9918
        return self::substr($haystack, (int) self::strlen($match[1]));
9919
    }
9920
9921
    /**
9922
     *  * Finds first occurrence of a string within another.
9923
     *
9924
     * @param string $haystack      <p>
9925
     *                              The string from which to get the first occurrence
9926
     *                              of needle.
9927
     *                              </p>
9928
     * @param string $needle        <p>
9929
     *                              The string to find in haystack.
9930
     *                              </p>
9931
     * @param bool   $before_needle [optional] <p>
9932
     *                              Determines which portion of haystack
9933
     *                              this function returns.
9934
     *                              If set to true, it returns all of haystack
9935
     *                              from the beginning to the first occurrence of needle.
9936
     *                              If set to false, it returns all of haystack
9937
     *                              from the first occurrence of needle to the end,
9938
     *                              </p>
9939
     *
9940
     * @return false|string
9941
     *                      <p>The portion of haystack,
9942
     *                      or false if needle is not found.</p>
9943
     */
9944
    public static function strstr_in_byte(
9945
        string $haystack,
9946
        string $needle,
9947
        bool $before_needle = false
9948
    ) {
9949
        if ($haystack === '' || $needle === '') {
9950
            return false;
9951
        }
9952
9953
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
9954
            // "mb_" is available if overload is used, so use it ...
9955
            return \mb_strstr($haystack, $needle, $before_needle, 'CP850'); // 8-BIT
9956
        }
9957
9958
        return \strstr($haystack, $needle, $before_needle);
9959
    }
9960
9961
    /**
9962
     * Unicode transformation for case-less matching.
9963
     *
9964
     * @see http://unicode.org/reports/tr21/tr21-5.html
9965
     *
9966
     * @param string      $str        <p>The input string.</p>
9967
     * @param bool        $full       [optional] <p>
9968
     *                                <b>true</b>, replace full case folding chars (default)<br>
9969
     *                                <b>false</b>, use only limited static array [UTF8::$COMMON_CASE_FOLD]
9970
     *                                </p>
9971
     * @param bool        $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
9972
     * @param string      $encoding   [optional] <p>Set the charset.</p>
9973
     * @param string|null $lang       [optional] <p>Set the language for special cases: az, el, lt, tr</p>
9974
     * @param bool        $lower      [optional] <p>Use lowercase string, otherwise use uppercase string. PS: uppercase
9975
     *                                is for some languages better ...</p>
9976
     *
9977
     * @return string
9978
     */
9979 32
    public static function strtocasefold(
9980
        string $str,
9981
        bool $full = true,
9982
        bool $clean_utf8 = false,
9983
        string $encoding = 'UTF-8',
9984
        string $lang = null,
9985
        $lower = true
9986
    ): string {
9987 32
        if ($str === '') {
9988 5
            return '';
9989
        }
9990
9991 31
        if ($clean_utf8 === true) {
9992
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
9993
            // if invalid characters are found in $haystack before $needle
9994 2
            $str = self::clean($str);
9995
        }
9996
9997 31
        $str = self::fixStrCaseHelper($str, $lower, $full);
9998
9999 31
        if ($lang === null && $encoding === 'UTF-8') {
10000 31
            if ($lower === true) {
10001 2
                return \mb_strtolower($str);
10002
            }
10003
10004 29
            return \mb_strtoupper($str);
10005
        }
10006
10007 2
        if ($lower === true) {
10008
            return self::strtolower($str, $encoding, false, $lang);
10009
        }
10010
10011 2
        return self::strtoupper($str, $encoding, false, $lang);
10012
    }
10013
10014
    /**
10015
     * Make a string lowercase.
10016
     *
10017
     * @see http://php.net/manual/en/function.mb-strtolower.php
10018
     *
10019
     * @param string      $str                           <p>The string being lowercased.</p>
10020
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
10021
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
10022
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt, tr</p>
10023
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
10024
     *
10025
     * @return string
10026
     *                <p>String with all alphabetic characters converted to lowercase.</p>
10027
     */
10028 73
    public static function strtolower(
10029
        $str,
10030
        string $encoding = 'UTF-8',
10031
        bool $clean_utf8 = false,
10032
        string $lang = null,
10033
        bool $try_to_keep_the_string_length = false
10034
    ): string {
10035
        // init
10036 73
        $str = (string) $str;
10037
10038 73
        if ($str === '') {
10039 1
            return '';
10040
        }
10041
10042 72
        if ($clean_utf8 === true) {
10043
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10044
            // if invalid characters are found in $haystack before $needle
10045 2
            $str = self::clean($str);
10046
        }
10047
10048
        // hack for old php version or for the polyfill ...
10049 72
        if ($try_to_keep_the_string_length === true) {
10050
            $str = self::fixStrCaseHelper($str, true);
10051
        }
10052
10053 72
        if ($lang === null && $encoding === 'UTF-8') {
10054 13
            return \mb_strtolower($str);
10055
        }
10056
10057 61
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
10058
10059 61
        if ($lang !== null) {
10060 2
            if (self::$SUPPORT['intl'] === true) {
10061 2
                if (self::$INTL_TRANSLITERATOR_LIST === null) {
10062
                    self::$INTL_TRANSLITERATOR_LIST = self::getData('transliterator_list');
10063
                }
10064
10065 2
                $language_code = $lang . '-Lower';
10066 2
                if (!\in_array($language_code, self::$INTL_TRANSLITERATOR_LIST, true)) {
10067
                    \trigger_error('UTF8::strtolower() cannot handle special language: ' . $lang . ' | supported: ' . \print_r(self::$INTL_TRANSLITERATOR_LIST, true), \E_USER_WARNING);
10068
10069
                    $language_code = 'Any-Lower';
10070
                }
10071
10072
                /** @noinspection PhpComposerExtensionStubsInspection */
10073
                /** @noinspection UnnecessaryCastingInspection */
10074 2
                return (string) \transliterator_transliterate($language_code, $str);
10075
            }
10076
10077
            \trigger_error('UTF8::strtolower() without intl cannot handle the "lang" parameter: ' . $lang, \E_USER_WARNING);
10078
        }
10079
10080
        // always fallback via symfony polyfill
10081 61
        return \mb_strtolower($str, $encoding);
10082
    }
10083
10084
    /**
10085
     * Make a string uppercase.
10086
     *
10087
     * @see http://php.net/manual/en/function.mb-strtoupper.php
10088
     *
10089
     * @param string      $str                           <p>The string being uppercased.</p>
10090
     * @param string      $encoding                      [optional] <p>Set the charset.</p>
10091
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
10092
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt, tr</p>
10093
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
10094
     *
10095
     * @return string
10096
     *                <p>String with all alphabetic characters converted to uppercase.</p>
10097
     */
10098 17
    public static function strtoupper(
10099
        $str,
10100
        string $encoding = 'UTF-8',
10101
        bool $clean_utf8 = false,
10102
        string $lang = null,
10103
        bool $try_to_keep_the_string_length = false
10104
    ): string {
10105
        // init
10106 17
        $str = (string) $str;
10107
10108 17
        if ($str === '') {
10109 1
            return '';
10110
        }
10111
10112 16
        if ($clean_utf8 === true) {
10113
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10114
            // if invalid characters are found in $haystack before $needle
10115 2
            $str = self::clean($str);
10116
        }
10117
10118
        // hack for old php version or for the polyfill ...
10119 16
        if ($try_to_keep_the_string_length === true) {
10120 2
            $str = self::fixStrCaseHelper($str, false);
10121
        }
10122
10123 16
        if ($lang === null && $encoding === 'UTF-8') {
10124 8
            return \mb_strtoupper($str);
10125
        }
10126
10127 10
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
10128
10129 10
        if ($lang !== null) {
10130 2
            if (self::$SUPPORT['intl'] === true) {
10131 2
                if (self::$INTL_TRANSLITERATOR_LIST === null) {
10132
                    self::$INTL_TRANSLITERATOR_LIST = self::getData('transliterator_list');
10133
                }
10134
10135 2
                $language_code = $lang . '-Upper';
10136 2
                if (!\in_array($language_code, self::$INTL_TRANSLITERATOR_LIST, true)) {
10137
                    \trigger_error('UTF8::strtoupper() without intl for special language: ' . $lang, \E_USER_WARNING);
10138
10139
                    $language_code = 'Any-Upper';
10140
                }
10141
10142
                /** @noinspection PhpComposerExtensionStubsInspection */
10143
                /** @noinspection UnnecessaryCastingInspection */
10144 2
                return (string) \transliterator_transliterate($language_code, $str);
10145
            }
10146
10147
            \trigger_error('UTF8::strtolower() without intl cannot handle the "lang"-parameter: ' . $lang, \E_USER_WARNING);
10148
        }
10149
10150
        // always fallback via symfony polyfill
10151 10
        return \mb_strtoupper($str, $encoding);
10152
    }
10153
10154
    /**
10155
     * Translate characters or replace sub-strings.
10156
     *
10157
     * @see http://php.net/manual/en/function.strtr.php
10158
     *
10159
     * @param string          $str  <p>The string being translated.</p>
10160
     * @param string|string[] $from <p>The string replacing from.</p>
10161
     * @param string|string[] $to   [optional] <p>The string being translated to to.</p>
10162
     *
10163
     * @return string
10164
     *                <p>This function returns a copy of str, translating all occurrences of each character in "from" to the
10165
     *                corresponding character in "to".</p>
10166
     */
10167 2
    public static function strtr(string $str, $from, $to = ''): string
10168
    {
10169 2
        if ($str === '') {
10170
            return '';
10171
        }
10172
10173 2
        if ($from === $to) {
10174
            return $str;
10175
        }
10176
10177 2
        if ($to !== '') {
10178 2
            $from = self::str_split($from);
10179 2
            $to = self::str_split($to);
10180 2
            $count_from = \count($from);
10181 2
            $count_to = \count($to);
10182
10183 2
            if ($count_from > $count_to) {
10184 2
                $from = \array_slice($from, 0, $count_to);
10185 2
            } elseif ($count_from < $count_to) {
10186 2
                $to = \array_slice($to, 0, $count_from);
10187
            }
10188
10189 2
            $from = \array_combine($from, $to);
10190
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
10191 2
            if ($from === false) {
10192
                throw new \InvalidArgumentException('The number of elements for each array isn\'t equal or the arrays are empty: (from: ' . \print_r($from, true) . ' | to: ' . \print_r($to, true) . ')');
10193
            }
10194
        }
10195
10196 2
        if (\is_string($from)) {
10197 2
            return \str_replace($from, '', $str);
10198
        }
10199
10200 2
        return \strtr($str, $from);
10201
    }
10202
10203
    /**
10204
     * Return the width of a string.
10205
     *
10206
     * @param string $str        <p>The input string.</p>
10207
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
10208
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
10209
     *
10210
     * @return int
10211
     */
10212 2
    public static function strwidth(
10213
        string $str,
10214
        string $encoding = 'UTF-8',
10215
        bool $clean_utf8 = false
10216
    ): int {
10217 2
        if ($str === '') {
10218 2
            return 0;
10219
        }
10220
10221 2
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
10222 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10223
        }
10224
10225 2
        if ($clean_utf8 === true) {
10226
            // iconv and mbstring are not tolerant to invalid encoding
10227
            // further, their behaviour is inconsistent with that of PHP's substr
10228 2
            $str = self::clean($str);
10229
        }
10230
10231
        //
10232
        // fallback via mbstring
10233
        //
10234
10235 2
        if (self::$SUPPORT['mbstring'] === true) {
10236 2
            if ($encoding === 'UTF-8') {
10237 2
                return \mb_strwidth($str);
10238
            }
10239
10240
            return \mb_strwidth($str, $encoding);
10241
        }
10242
10243
        //
10244
        // fallback via vanilla php
10245
        //
10246
10247
        if ($encoding !== 'UTF-8') {
10248
            $str = self::encode('UTF-8', $str, false, $encoding);
10249
        }
10250
10251
        $wide = 0;
10252
        $str = (string) \preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $str, -1, $wide);
10253
10254
        return ($wide << 1) + (int) self::strlen($str, 'UTF-8');
10255
    }
10256
10257
    /**
10258
     * Get part of a string.
10259
     *
10260
     * @see http://php.net/manual/en/function.mb-substr.php
10261
     *
10262
     * @param string $str        <p>The string being checked.</p>
10263
     * @param int    $offset     <p>The first position used in str.</p>
10264
     * @param int    $length     [optional] <p>The maximum length of the returned string.</p>
10265
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
10266
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
10267
     *
10268
     * @return false|string
10269
     *                      The portion of <i>str</i> specified by the <i>offset</i> and
10270
     *                      <i>length</i> parameters.</p><p>If <i>str</i> is shorter than <i>offset</i>
10271
     *                      characters long, <b>FALSE</b> will be returned.
10272
     */
10273 172
    public static function substr(
10274
        string $str,
10275
        int $offset = 0,
10276
        int $length = null,
10277
        string $encoding = 'UTF-8',
10278
        bool $clean_utf8 = false
10279
    ) {
10280
        // empty string
10281 172
        if ($str === '' || $length === 0) {
10282 8
            return '';
10283
        }
10284
10285 168
        if ($clean_utf8 === true) {
10286
            // iconv and mbstring are not tolerant to invalid encoding
10287
            // further, their behaviour is inconsistent with that of PHP's substr
10288 2
            $str = self::clean($str);
10289
        }
10290
10291
        // whole string
10292 168
        if (!$offset && $length === null) {
10293 7
            return $str;
10294
        }
10295
10296 163
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
10297 19
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10298
        }
10299
10300
        //
10301
        // fallback via mbstring
10302
        //
10303
10304 163
        if (self::$SUPPORT['mbstring'] === true) {
10305 161
            if ($encoding === 'UTF-8') {
10306 161
                if ($length === null) {
10307 64
                    return \mb_substr($str, $offset);
10308
                }
10309
10310 102
                return \mb_substr($str, $offset, $length);
10311
            }
10312
10313
            return self::substr($str, $offset, $length, $encoding);
10314
        }
10315
10316
        //
10317
        // fallback for binary || ascii only
10318
        //
10319
10320
        if (
10321 4
            $encoding === 'CP850'
10322
            ||
10323 4
            $encoding === 'ASCII'
10324
        ) {
10325
            if ($length === null) {
10326
                return \substr($str, $offset);
10327
            }
10328
10329
            return \substr($str, $offset, $length);
10330
        }
10331
10332
        // otherwise we need the string-length
10333 4
        $str_length = 0;
10334 4
        if ($offset || $length === null) {
10335 4
            $str_length = self::strlen($str, $encoding);
10336
        }
10337
10338
        // e.g.: invalid chars + mbstring not installed
10339 4
        if ($str_length === false) {
10340
            return false;
10341
        }
10342
10343
        // empty string
10344 4
        if ($offset === $str_length && !$length) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $length of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
10345
            return '';
10346
        }
10347
10348
        // impossible
10349 4
        if ($offset && $offset > $str_length) {
10350
            return '';
10351
        }
10352
10353 4
        if ($length === null) {
10354 4
            $length = (int) $str_length;
10355
        } else {
10356 2
            $length = (int) $length;
10357
        }
10358
10359
        if (
10360 4
            $encoding !== 'UTF-8'
10361
            &&
10362 4
            self::$SUPPORT['mbstring'] === false
10363
        ) {
10364 2
            \trigger_error('UTF8::substr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
10365
        }
10366
10367
        //
10368
        // fallback via intl
10369
        //
10370
10371
        if (
10372 4
            $encoding === 'UTF-8' // INFO: "grapheme_substr()" can't handle other encodings
10373
            &&
10374 4
            $offset >= 0 // grapheme_substr() can't handle negative offset
10375
            &&
10376 4
            self::$SUPPORT['intl'] === true
10377
        ) {
10378
            $return_tmp = \grapheme_substr($str, $offset, $length);
10379
            if ($return_tmp !== false) {
10380
                return $return_tmp;
10381
            }
10382
        }
10383
10384
        //
10385
        // fallback via iconv
10386
        //
10387
10388
        if (
10389 4
            $length >= 0 // "iconv_substr()" can't handle negative length
10390
            &&
10391 4
            self::$SUPPORT['iconv'] === true
10392
        ) {
10393
            $return_tmp = \iconv_substr($str, $offset, $length);
10394
            if ($return_tmp !== false) {
10395
                return $return_tmp;
10396
            }
10397
        }
10398
10399
        //
10400
        // fallback for ascii only
10401
        //
10402
10403 4
        if (ASCII::is_ascii($str)) {
10404
            return \substr($str, $offset, $length);
10405
        }
10406
10407
        //
10408
        // fallback via vanilla php
10409
        //
10410
10411
        // split to array, and remove invalid characters
10412 4
        $array = self::str_split($str);
10413
10414
        // extract relevant part, and join to make sting again
10415 4
        return \implode('', \array_slice($array, $offset, $length));
10416
    }
10417
10418
    /**
10419
     * Binary-safe comparison of two strings from an offset, up to a length of characters.
10420
     *
10421
     * @param string   $str1               <p>The main string being compared.</p>
10422
     * @param string   $str2               <p>The secondary string being compared.</p>
10423
     * @param int      $offset             [optional] <p>The start position for the comparison. If negative, it starts
10424
     *                                     counting from the end of the string.</p>
10425
     * @param int|null $length             [optional] <p>The length of the comparison. The default value is the largest
10426
     *                                     of the length of the str compared to the length of main_str less the
10427
     *                                     offset.</p>
10428
     * @param bool     $case_insensitivity [optional] <p>If case_insensitivity is TRUE, comparison is case
10429
     *                                     insensitive.</p>
10430
     * @param string   $encoding           [optional] <p>Set the charset for e.g. "mb_" function</p>
10431
     *
10432
     * @return int
10433
     *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
10434
     *             <strong>&gt; 0</strong> if str1 is greater than str2,<br>
10435
     *             <strong>0</strong> if they are equal
10436
     */
10437 2
    public static function substr_compare(
10438
        string $str1,
10439
        string $str2,
10440
        int $offset = 0,
10441
        int $length = null,
10442
        bool $case_insensitivity = false,
10443
        string $encoding = 'UTF-8'
10444
    ): int {
10445
        if (
10446 2
            $offset !== 0
10447
            ||
10448 2
            $length !== null
10449
        ) {
10450 2
            if ($encoding === 'UTF-8') {
10451 2
                if ($length === null) {
10452 2
                    $str1 = (string) \mb_substr($str1, $offset);
10453
                } else {
10454 2
                    $str1 = (string) \mb_substr($str1, $offset, $length);
10455
                }
10456 2
                $str2 = (string) \mb_substr($str2, 0, (int) self::strlen($str1));
10457
            } else {
10458
                $encoding = self::normalize_encoding($encoding, 'UTF-8');
10459
10460
                $str1 = (string) self::substr($str1, $offset, $length, $encoding);
10461
                $str2 = (string) self::substr($str2, 0, (int) self::strlen($str1), $encoding);
10462
            }
10463
        }
10464
10465 2
        if ($case_insensitivity === true) {
10466 2
            return self::strcasecmp($str1, $str2, $encoding);
10467
        }
10468
10469 2
        return self::strcmp($str1, $str2);
10470
    }
10471
10472
    /**
10473
     * Count the number of substring occurrences.
10474
     *
10475
     * @see http://php.net/manual/en/function.substr-count.php
10476
     *
10477
     * @param string $haystack   <p>The string to search in.</p>
10478
     * @param string $needle     <p>The substring to search for.</p>
10479
     * @param int    $offset     [optional] <p>The offset where to start counting.</p>
10480
     * @param int    $length     [optional] <p>
10481
     *                           The maximum length after the specified offset to search for the
10482
     *                           substring. It outputs a warning if the offset plus the length is
10483
     *                           greater than the haystack length.
10484
     *                           </p>
10485
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
10486
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
10487
     *
10488
     * @return false|int this functions returns an integer or false if there isn't a string
10489
     */
10490 5
    public static function substr_count(
10491
        string $haystack,
10492
        string $needle,
10493
        int $offset = 0,
10494
        int $length = null,
10495
        string $encoding = 'UTF-8',
10496
        bool $clean_utf8 = false
10497
    ) {
10498 5
        if ($haystack === '' || $needle === '') {
10499 2
            return false;
10500
        }
10501
10502 5
        if ($length === 0) {
10503 2
            return 0;
10504
        }
10505
10506 5
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
10507 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10508
        }
10509
10510 5
        if ($clean_utf8 === true) {
10511
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10512
            // if invalid characters are found in $haystack before $needle
10513
            $needle = self::clean($needle);
10514
            $haystack = self::clean($haystack);
10515
        }
10516
10517 5
        if ($offset || $length > 0) {
10518 2
            if ($length === null) {
10519 2
                $length_tmp = self::strlen($haystack, $encoding);
10520 2
                if ($length_tmp === false) {
10521
                    return false;
10522
                }
10523 2
                $length = (int) $length_tmp;
10524
            }
10525
10526 2
            if ($encoding === 'UTF-8') {
10527 2
                $haystack = (string) \mb_substr($haystack, $offset, $length);
10528
            } else {
10529 2
                $haystack = (string) \mb_substr($haystack, $offset, $length, $encoding);
10530
            }
10531
        }
10532
10533
        if (
10534 5
            $encoding !== 'UTF-8'
10535
            &&
10536 5
            self::$SUPPORT['mbstring'] === false
10537
        ) {
10538
            \trigger_error('UTF8::substr_count() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
10539
        }
10540
10541 5
        if (self::$SUPPORT['mbstring'] === true) {
10542 5
            if ($encoding === 'UTF-8') {
10543 5
                return \mb_substr_count($haystack, $needle);
10544
            }
10545
10546 2
            return \mb_substr_count($haystack, $needle, $encoding);
10547
        }
10548
10549
        \preg_match_all('/' . \preg_quote($needle, '/') . '/us', $haystack, $matches, \PREG_SET_ORDER);
10550
10551
        return \count($matches);
10552
    }
10553
10554
    /**
10555
     * Count the number of substring occurrences.
10556
     *
10557
     * @param string $haystack <p>
10558
     *                         The string being checked.
10559
     *                         </p>
10560
     * @param string $needle   <p>
10561
     *                         The string being found.
10562
     *                         </p>
10563
     * @param int    $offset   [optional] <p>
10564
     *                         The offset where to start counting
10565
     *                         </p>
10566
     * @param int    $length   [optional] <p>
10567
     *                         The maximum length after the specified offset to search for the
10568
     *                         substring. It outputs a warning if the offset plus the length is
10569
     *                         greater than the haystack length.
10570
     *                         </p>
10571
     *
10572
     * @return false|int the number of times the
10573
     *                   needle substring occurs in the
10574
     *                   haystack string
10575
     */
10576
    public static function substr_count_in_byte(
10577
        string $haystack,
10578
        string $needle,
10579
        int $offset = 0,
10580
        int $length = null
10581
    ) {
10582
        if ($haystack === '' || $needle === '') {
10583
            return 0;
10584
        }
10585
10586
        if (
10587
            ($offset || $length !== null)
10588
            &&
10589
            self::$SUPPORT['mbstring_func_overload'] === true
10590
        ) {
10591
            if ($length === null) {
10592
                $length_tmp = self::strlen($haystack);
10593
                if ($length_tmp === false) {
10594
                    return false;
10595
                }
10596
                $length = (int) $length_tmp;
10597
            }
10598
10599
            if (
10600
                (
10601
                    $length !== 0
10602
                    &&
10603
                    $offset !== 0
10604
                )
10605
                &&
10606
                ($length + $offset) <= 0
10607
                &&
10608
                Bootup::is_php('7.1') === false // output from "substr_count()" have changed in PHP 7.1
10609
            ) {
10610
                return false;
10611
            }
10612
10613
            /** @var string|false $haystack_tmp - needed for PhpStan (stubs error) */
10614
            $haystack_tmp = \substr($haystack, $offset, $length);
10615
            if ($haystack_tmp === false) {
10616
                $haystack_tmp = '';
10617
            }
10618
            $haystack = (string) $haystack_tmp;
10619
        }
10620
10621
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
10622
            // "mb_" is available if overload is used, so use it ...
10623
            return \mb_substr_count($haystack, $needle, 'CP850'); // 8-BIT
10624
        }
10625
10626
        if ($length === null) {
10627
            return \substr_count($haystack, $needle, $offset);
10628
        }
10629
10630
        return \substr_count($haystack, $needle, $offset, $length);
10631
    }
10632
10633
    /**
10634
     * Returns the number of occurrences of $substring in the given string.
10635
     * By default, the comparison is case-sensitive, but can be made insensitive
10636
     * by setting $case_sensitive to false.
10637
     *
10638
     * @param string $str            <p>The input string.</p>
10639
     * @param string $substring      <p>The substring to search for.</p>
10640
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
10641
     * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
10642
     *
10643
     * @return int
10644
     */
10645 15
    public static function substr_count_simple(
10646
        string $str,
10647
        string $substring,
10648
        bool $case_sensitive = true,
10649
        string $encoding = 'UTF-8'
10650
    ): int {
10651 15
        if ($str === '' || $substring === '') {
10652 2
            return 0;
10653
        }
10654
10655 13
        if ($encoding === 'UTF-8') {
10656 7
            if ($case_sensitive) {
10657
                return (int) \mb_substr_count($str, $substring);
10658
            }
10659
10660 7
            return (int) \mb_substr_count(
10661 7
                \mb_strtoupper($str),
10662 7
                \mb_strtoupper($substring)
10663
            );
10664
        }
10665
10666 6
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
10667
10668 6
        if ($case_sensitive) {
10669 3
            return (int) \mb_substr_count($str, $substring, $encoding);
10670
        }
10671
10672 3
        return (int) \mb_substr_count(
10673 3
            self::strtocasefold($str, true, false, $encoding, null, false),
10674 3
            self::strtocasefold($substring, true, false, $encoding, null, false),
10675 3
            $encoding
10676
        );
10677
    }
10678
10679
    /**
10680
     * Removes a prefix ($needle) from the beginning of the string ($haystack), case-insensitive.
10681
     *
10682
     * @param string $haystack <p>The string to search in.</p>
10683
     * @param string $needle   <p>The substring to search for.</p>
10684
     *
10685
     * @return string return the sub-string
10686
     */
10687 2
    public static function substr_ileft(string $haystack, string $needle): string
10688
    {
10689 2
        if ($haystack === '') {
10690 2
            return '';
10691
        }
10692
10693 2
        if ($needle === '') {
10694 2
            return $haystack;
10695
        }
10696
10697 2
        if (self::str_istarts_with($haystack, $needle) === true) {
10698 2
            $haystack = (string) \mb_substr($haystack, (int) self::strlen($needle));
10699
        }
10700
10701 2
        return $haystack;
10702
    }
10703
10704
    /**
10705
     * Get part of a string process in bytes.
10706
     *
10707
     * @param string $str    <p>The string being checked.</p>
10708
     * @param int    $offset <p>The first position used in str.</p>
10709
     * @param int    $length [optional] <p>The maximum length of the returned string.</p>
10710
     *
10711
     * @return false|string
10712
     *                      The portion of <i>str</i> specified by the <i>offset</i> and
10713
     *                      <i>length</i> parameters.</p><p>If <i>str</i> is shorter than <i>offset</i>
10714
     *                      characters long, <b>FALSE</b> will be returned.
10715
     */
10716
    public static function substr_in_byte(string $str, int $offset = 0, int $length = null)
10717
    {
10718
        // empty string
10719
        if ($str === '' || $length === 0) {
10720
            return '';
10721
        }
10722
10723
        // whole string
10724
        if (!$offset && $length === null) {
10725
            return $str;
10726
        }
10727
10728
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
10729
            // "mb_" is available if overload is used, so use it ...
10730
            return \mb_substr($str, $offset, $length, 'CP850'); // 8-BIT
10731
        }
10732
10733
        return \substr($str, $offset, $length ?? 2147483647);
10734
    }
10735
10736
    /**
10737
     * Removes a suffix ($needle) from the end of the string ($haystack), case-insensitive.
10738
     *
10739
     * @param string $haystack <p>The string to search in.</p>
10740
     * @param string $needle   <p>The substring to search for.</p>
10741
     *
10742
     * @return string return the sub-string
10743
     */
10744 2
    public static function substr_iright(string $haystack, string $needle): string
10745
    {
10746 2
        if ($haystack === '') {
10747 2
            return '';
10748
        }
10749
10750 2
        if ($needle === '') {
10751 2
            return $haystack;
10752
        }
10753
10754 2
        if (self::str_iends_with($haystack, $needle) === true) {
10755 2
            $haystack = (string) \mb_substr($haystack, 0, (int) self::strlen($haystack) - (int) self::strlen($needle));
10756
        }
10757
10758 2
        return $haystack;
10759
    }
10760
10761
    /**
10762
     * Removes a prefix ($needle) from the beginning of the string ($haystack).
10763
     *
10764
     * @param string $haystack <p>The string to search in.</p>
10765
     * @param string $needle   <p>The substring to search for.</p>
10766
     *
10767
     * @return string return the sub-string
10768
     */
10769 2
    public static function substr_left(string $haystack, string $needle): string
10770
    {
10771 2
        if ($haystack === '') {
10772 2
            return '';
10773
        }
10774
10775 2
        if ($needle === '') {
10776 2
            return $haystack;
10777
        }
10778
10779 2
        if (self::str_starts_with($haystack, $needle) === true) {
10780 2
            $haystack = (string) \mb_substr($haystack, (int) self::strlen($needle));
10781
        }
10782
10783 2
        return $haystack;
10784
    }
10785
10786
    /**
10787
     * Replace text within a portion of a string.
10788
     *
10789
     * source: https://gist.github.com/stemar/8287074
10790
     *
10791
     * @param string|string[] $str         <p>The input string or an array of stings.</p>
10792
     * @param string|string[] $replacement <p>The replacement string or an array of stings.</p>
10793
     * @param int|int[]       $offset      <p>
10794
     *                                     If start is positive, the replacing will begin at the start'th offset
10795
     *                                     into string.
10796
     *                                     <br><br>
10797
     *                                     If start is negative, the replacing will begin at the start'th character
10798
     *                                     from the end of string.
10799
     *                                     </p>
10800
     * @param int|int[]|null  $length      [optional] <p>If given and is positive, it represents the length of the
10801
     *                                     portion of string which is to be replaced. If it is negative, it
10802
     *                                     represents the number of characters from the end of string at which to
10803
     *                                     stop replacing. If it is not given, then it will default to strlen(
10804
     *                                     string ); i.e. end the replacing at the end of string. Of course, if
10805
     *                                     length is zero then this function will have the effect of inserting
10806
     *                                     replacement into string at the given start offset.</p>
10807
     * @param string          $encoding    [optional] <p>Set the charset for e.g. "mb_" function</p>
10808
     *
10809
     * @return string|string[] The result string is returned. If string is an array then array is returned.
10810
     */
10811 10
    public static function substr_replace(
10812
        $str,
10813
        $replacement,
10814
        $offset,
10815
        $length = null,
10816
        string $encoding = 'UTF-8'
10817
    ) {
10818 10
        if (\is_array($str) === true) {
10819 1
            $num = \count($str);
10820
10821
            // the replacement
10822 1
            if (\is_array($replacement) === true) {
10823 1
                $replacement = \array_slice($replacement, 0, $num);
10824
            } else {
10825 1
                $replacement = \array_pad([$replacement], $num, $replacement);
10826
            }
10827
10828
            // the offset
10829 1
            if (\is_array($offset) === true) {
10830 1
                $offset = \array_slice($offset, 0, $num);
10831 1
                foreach ($offset as &$value_tmp) {
10832 1
                    $value_tmp = (int) $value_tmp === $value_tmp ? $value_tmp : 0;
10833
                }
10834 1
                unset($value_tmp);
10835
            } else {
10836 1
                $offset = \array_pad([$offset], $num, $offset);
10837
            }
10838
10839
            // the length
10840 1
            if ($length === null) {
10841 1
                $length = \array_fill(0, $num, 0);
10842 1
            } elseif (\is_array($length) === true) {
10843 1
                $length = \array_slice($length, 0, $num);
10844 1
                foreach ($length as &$value_tmp_V2) {
10845 1
                    $value_tmp_V2 = (int) $value_tmp_V2 === $value_tmp_V2 ? $value_tmp_V2 : $num;
10846
                }
10847 1
                unset($value_tmp_V2);
10848
            } else {
10849 1
                $length = \array_pad([$length], $num, $length);
10850
            }
10851
10852
            // recursive call
10853 1
            return \array_map([self::class, 'substr_replace'], $str, $replacement, $offset, $length);
10854
        }
10855
10856 10
        if (\is_array($replacement) === true) {
10857 1
            if (\count($replacement) > 0) {
10858 1
                $replacement = $replacement[0];
10859
            } else {
10860 1
                $replacement = '';
10861
            }
10862
        }
10863
10864
        // init
10865 10
        $str = (string) $str;
10866 10
        $replacement = (string) $replacement;
10867
10868 10
        if (\is_array($length) === true) {
10869
            throw new \InvalidArgumentException('Parameter "$length" can only be an array, if "$str" is also an array.');
10870
        }
10871
10872 10
        if (\is_array($offset) === true) {
10873
            throw new \InvalidArgumentException('Parameter "$offset" can only be an array, if "$str" is also an array.');
10874
        }
10875
10876 10
        if ($str === '') {
10877 1
            return $replacement;
10878
        }
10879
10880 9
        if (self::$SUPPORT['mbstring'] === true) {
10881 9
            $string_length = (int) self::strlen($str, $encoding);
10882
10883 9
            if ($offset < 0) {
10884 1
                $offset = (int) \max(0, $string_length + $offset);
10885 9
            } elseif ($offset > $string_length) {
10886 1
                $offset = $string_length;
10887
            }
10888
10889 9
            if ($length !== null && $length < 0) {
10890 1
                $length = (int) \max(0, $string_length - $offset + $length);
10891 9
            } elseif ($length === null || $length > $string_length) {
10892 4
                $length = $string_length;
10893
            }
10894
10895
            /** @noinspection AdditionOperationOnArraysInspection */
10896 9
            if (($offset + $length) > $string_length) {
10897 4
                $length = $string_length - $offset;
10898
            }
10899
10900
            /** @noinspection AdditionOperationOnArraysInspection */
10901 9
            return ((string) \mb_substr($str, 0, $offset, $encoding)) .
10902 9
                   $replacement .
10903 9
                   ((string) \mb_substr($str, $offset + $length, $string_length - $offset - $length, $encoding));
10904
        }
10905
10906
        //
10907
        // fallback for ascii only
10908
        //
10909
10910
        if (ASCII::is_ascii($str)) {
10911
            return ($length === null) ?
10912
                \substr_replace($str, $replacement, $offset) :
10913
                \substr_replace($str, $replacement, $offset, $length);
10914
        }
10915
10916
        //
10917
        // fallback via vanilla php
10918
        //
10919
10920
        \preg_match_all('/./us', $str, $str_matches);
10921
        \preg_match_all('/./us', $replacement, $replacement_matches);
10922
10923
        if ($length === null) {
10924
            $length_tmp = self::strlen($str, $encoding);
10925
            if ($length_tmp === false) {
10926
                // e.g.: non mbstring support + invalid chars
10927
                return '';
10928
            }
10929
            $length = (int) $length_tmp;
10930
        }
10931
10932
        \array_splice($str_matches[0], $offset, $length, $replacement_matches[0]);
10933
10934
        return \implode('', $str_matches[0]);
10935
    }
10936
10937
    /**
10938
     * Removes a suffix ($needle) from the end of the string ($haystack).
10939
     *
10940
     * @param string $haystack <p>The string to search in.</p>
10941
     * @param string $needle   <p>The substring to search for.</p>
10942
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
10943
     *
10944
     * @return string return the sub-string
10945
     */
10946 2
    public static function substr_right(
10947
        string $haystack,
10948
        string $needle,
10949
        string $encoding = 'UTF-8'
10950
    ): string {
10951 2
        if ($haystack === '') {
10952 2
            return '';
10953
        }
10954
10955 2
        if ($needle === '') {
10956 2
            return $haystack;
10957
        }
10958
10959
        if (
10960 2
            $encoding === 'UTF-8'
10961
            &&
10962 2
            \substr($haystack, -\strlen($needle)) === $needle
10963
        ) {
10964 2
            return (string) \mb_substr($haystack, 0, (int) \mb_strlen($haystack) - (int) \mb_strlen($needle));
10965
        }
10966
10967 2
        if (\substr($haystack, -\strlen($needle)) === $needle) {
10968
            return (string) self::substr(
10969
                $haystack,
10970
                0,
10971
                (int) self::strlen($haystack, $encoding) - (int) self::strlen($needle, $encoding),
10972
                $encoding
10973
            );
10974
        }
10975
10976 2
        return $haystack;
10977
    }
10978
10979
    /**
10980
     * Returns a case swapped version of the string.
10981
     *
10982
     * @param string $str        <p>The input string.</p>
10983
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
10984
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
10985
     *
10986
     * @return string each character's case swapped
10987
     */
10988 6
    public static function swapCase(string $str, string $encoding = 'UTF-8', bool $clean_utf8 = false): string
10989
    {
10990 6
        if ($str === '') {
10991 1
            return '';
10992
        }
10993
10994 6
        if ($clean_utf8 === true) {
10995
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10996
            // if invalid characters are found in $haystack before $needle
10997 2
            $str = self::clean($str);
10998
        }
10999
11000 6
        if ($encoding === 'UTF-8') {
11001 4
            return (string) (\mb_strtolower($str) ^ \mb_strtoupper($str) ^ $str);
11002
        }
11003
11004 4
        return (string) (self::strtolower($str, $encoding) ^ self::strtoupper($str, $encoding) ^ $str);
11005
    }
11006
11007
    /**
11008
     * Checks whether symfony-polyfills are used.
11009
     *
11010
     * @return bool
11011
     *              <strong>true</strong> if in use, <strong>false</strong> otherwise
11012
     */
11013
    public static function symfony_polyfill_used(): bool
11014
    {
11015
        // init
11016
        $return = false;
11017
11018
        $return_tmp = \extension_loaded('mbstring');
11019
        if ($return_tmp === false && \function_exists('mb_strlen')) {
11020
            $return = true;
11021
        }
11022
11023
        $return_tmp = \extension_loaded('iconv');
11024
        if ($return_tmp === false && \function_exists('iconv')) {
11025
            $return = true;
11026
        }
11027
11028
        return $return;
11029
    }
11030
11031
    /**
11032
     * @param string $str
11033
     * @param int    $tab_length
11034
     *
11035
     * @return string
11036
     */
11037 6
    public static function tabs_to_spaces(string $str, int $tab_length = 4): string
11038
    {
11039 6
        if ($tab_length === 4) {
11040 3
            $spaces = '    ';
11041 3
        } elseif ($tab_length === 2) {
11042 1
            $spaces = '  ';
11043
        } else {
11044 2
            $spaces = \str_repeat(' ', $tab_length);
11045
        }
11046
11047 6
        return \str_replace("\t", $spaces, $str);
11048
    }
11049
11050
    /**
11051
     * Converts the first character of each word in the string to uppercase
11052
     * and all other chars to lowercase.
11053
     *
11054
     * @param string      $str                           <p>The input string.</p>
11055
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
11056
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
11057
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt, tr</p>
11058
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
11059
     *
11060
     * @return string
11061
     *                <p>A string with all characters of $str being title-cased.</p>
11062
     */
11063 5
    public static function titlecase(
11064
        string $str,
11065
        string $encoding = 'UTF-8',
11066
        bool $clean_utf8 = false,
11067
        string $lang = null,
11068
        bool $try_to_keep_the_string_length = false
11069
    ): string {
11070 5
        if ($clean_utf8 === true) {
11071
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11072
            // if invalid characters are found in $haystack before $needle
11073
            $str = self::clean($str);
11074
        }
11075
11076 5
        if ($lang === null && $try_to_keep_the_string_length === false) {
11077 5
            if ($encoding === 'UTF-8') {
11078 3
                return \mb_convert_case($str, \MB_CASE_TITLE);
11079
            }
11080
11081 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11082
11083 2
            return \mb_convert_case($str, \MB_CASE_TITLE, $encoding);
11084
        }
11085
11086
        return self::str_titleize(
11087
            $str,
11088
            null,
11089
            $encoding,
11090
            false,
11091
            $lang,
11092
            $try_to_keep_the_string_length,
11093
            false
11094
        );
11095
    }
11096
11097
    /**
11098
     * alias for "UTF8::to_ascii()"
11099
     *
11100
     * @param string $str
11101
     * @param string $subst_chr
11102
     * @param bool   $strict
11103
     *
11104
     * @return string
11105
     *
11106
     * @see UTF8::to_ascii()
11107
     * @deprecated <p>please use "UTF8::to_ascii()"</p>
11108
     */
11109 7
    public static function toAscii(
11110
        string $str,
11111
        string $subst_chr = '?',
11112
        bool $strict = false
11113
    ): string {
11114 7
        return self::to_ascii($str, $subst_chr, $strict);
11115
    }
11116
11117
    /**
11118
     * alias for "UTF8::to_iso8859()"
11119
     *
11120
     * @param string|string[] $str
11121
     *
11122
     * @return string|string[]
11123
     *
11124
     * @see UTF8::to_iso8859()
11125
     * @deprecated <p>please use "UTF8::to_iso8859()"</p>
11126
     */
11127 2
    public static function toIso8859($str)
11128
    {
11129 2
        return self::to_iso8859($str);
11130
    }
11131
11132
    /**
11133
     * alias for "UTF8::to_latin1()"
11134
     *
11135
     * @param string|string[] $str
11136
     *
11137
     * @return string|string[]
11138
     *
11139
     * @see UTF8::to_iso8859()
11140
     * @deprecated <p>please use "UTF8::to_iso8859()"</p>
11141
     */
11142 2
    public static function toLatin1($str)
11143
    {
11144 2
        return self::to_iso8859($str);
11145
    }
11146
11147
    /**
11148
     * alias for "UTF8::to_utf8()"
11149
     *
11150
     * @param string|string[] $str
11151
     *
11152
     * @return string|string[]
11153
     *
11154
     * @see UTF8::to_utf8()
11155
     * @deprecated <p>please use "UTF8::to_utf8()"</p>
11156
     */
11157 2
    public static function toUTF8($str)
11158
    {
11159 2
        return self::to_utf8($str);
11160
    }
11161
11162
    /**
11163
     * Convert a string into ASCII.
11164
     *
11165
     * @param string $str     <p>The input string.</p>
11166
     * @param string $unknown [optional] <p>Character use if character unknown. (default is ?)</p>
11167
     * @param bool   $strict  [optional] <p>Use "transliterator_transliterate()" from PHP-Intl | WARNING: bad
11168
     *                        performance</p>
11169
     *
11170
     * @return string
11171
     */
11172 37
    public static function to_ascii(
11173
        string $str,
11174
        string $unknown = '?',
11175
        bool $strict = false
11176
    ): string {
11177 37
        return ASCII::to_transliterate($str, $unknown, $strict);
11178
    }
11179
11180
    /**
11181
     * @param mixed $str
11182
     *
11183
     * @return bool
11184
     */
11185 19
    public static function to_boolean($str): bool
11186
    {
11187
        // init
11188 19
        $str = (string) $str;
11189
11190 19
        if ($str === '') {
11191 2
            return false;
11192
        }
11193
11194
        // Info: http://php.net/manual/en/filter.filters.validate.php
11195
        $map = [
11196 17
            'true'  => true,
11197
            '1'     => true,
11198
            'on'    => true,
11199
            'yes'   => true,
11200
            'false' => false,
11201
            '0'     => false,
11202
            'off'   => false,
11203
            'no'    => false,
11204
        ];
11205
11206 17
        if (isset($map[$str])) {
11207 11
            return $map[$str];
11208
        }
11209
11210 6
        $key = \strtolower($str);
11211 6
        if (isset($map[$key])) {
11212 2
            return $map[$key];
11213
        }
11214
11215 4
        if (\is_numeric($str)) {
11216 2
            return ((float) $str + 0) > 0;
11217
        }
11218
11219 2
        return (bool) \trim($str);
11220
    }
11221
11222
    /**
11223
     * Convert given string to safe filename (and keep string case).
11224
     *
11225
     * @param string $str
11226
     * @param bool   $use_transliterate No transliteration, conversion etc. is done by default - unsafe characters are
11227
     *                                  simply replaced with hyphen.
11228
     * @param string $fallback_char
11229
     *
11230
     * @return string
11231
     */
11232 1
    public static function to_filename(
11233
        string $str,
11234
        bool $use_transliterate = false,
11235
        string $fallback_char = '-'
11236
    ): string {
11237 1
        return ASCII::to_filename(
11238 1
            $str,
11239 1
            $use_transliterate,
11240 1
            $fallback_char
11241
        );
11242
    }
11243
11244
    /**
11245
     * Convert a string into "ISO-8859"-encoding (Latin-1).
11246
     *
11247
     * @param string|string[] $str
11248
     *
11249
     * @return string|string[]
11250
     */
11251 8
    public static function to_iso8859($str)
11252
    {
11253 8
        if (\is_array($str) === true) {
11254 2
            foreach ($str as $k => &$v) {
11255 2
                $v = self::to_iso8859($v);
11256
            }
11257
11258 2
            return $str;
11259
        }
11260
11261 8
        $str = (string) $str;
11262 8
        if ($str === '') {
11263 2
            return '';
11264
        }
11265
11266 8
        return self::utf8_decode($str);
11267
    }
11268
11269
    /**
11270
     * alias for "UTF8::to_iso8859()"
11271
     *
11272
     * @param string|string[] $str
11273
     *
11274
     * @return string|string[]
11275
     *
11276
     * @see UTF8::to_iso8859()
11277
     * @deprecated <p>please use "UTF8::to_iso8859()"</p>
11278
     */
11279 2
    public static function to_latin1($str)
11280
    {
11281 2
        return self::to_iso8859($str);
11282
    }
11283
11284
    /**
11285
     * This function leaves UTF-8 characters alone, while converting almost all non-UTF8 to UTF8.
11286
     *
11287
     * <ul>
11288
     * <li>It decode UTF-8 codepoints and Unicode escape sequences.</li>
11289
     * <li>It assumes that the encoding of the original string is either WINDOWS-1252 or ISO-8859.</li>
11290
     * <li>WARNING: It does not remove invalid UTF-8 characters, so you maybe need to use "UTF8::clean()" for this
11291
     * case.</li>
11292
     * </ul>
11293
     *
11294
     * @param string|string[] $str                        <p>Any string or array.</p>
11295
     * @param bool            $decode_html_entity_to_utf8 <p>Set to true, if you need to decode html-entities.</p>
11296
     *
11297
     * @return string|string[] the UTF-8 encoded string
11298
     */
11299 41
    public static function to_utf8($str, bool $decode_html_entity_to_utf8 = false)
11300
    {
11301 41
        if (\is_array($str) === true) {
11302 4
            foreach ($str as $k => &$v) {
11303 4
                $v = self::to_utf8($v, $decode_html_entity_to_utf8);
11304
            }
11305
11306 4
            return $str;
11307
        }
11308
11309 41
        $str = (string) $str;
11310 41
        if ($str === '') {
11311 6
            return $str;
11312
        }
11313
11314 41
        $max = \strlen($str);
11315 41
        $buf = '';
11316
11317 41
        for ($i = 0; $i < $max; ++$i) {
11318 41
            $c1 = $str[$i];
11319
11320 41
            if ($c1 >= "\xC0") { // should be converted to UTF8, if it's not UTF8 already
11321
11322 37
                if ($c1 <= "\xDF") { // looks like 2 bytes UTF8
11323
11324 34
                    $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
11325
11326 34
                    if ($c2 >= "\x80" && $c2 <= "\xBF") { // yeah, almost sure it's UTF8 already
11327 20
                        $buf .= $c1 . $c2;
11328 20
                        ++$i;
11329
                    } else { // not valid UTF8 - convert it
11330 34
                        $buf .= self::to_utf8_convert_helper($c1);
11331
                    }
11332 34
                } elseif ($c1 >= "\xE0" && $c1 <= "\xEF") { // looks like 3 bytes UTF8
11333
11334 33
                    $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
11335 33
                    $c3 = $i + 2 >= $max ? "\x00" : $str[$i + 2];
11336
11337 33
                    if ($c2 >= "\x80" && $c2 <= "\xBF" && $c3 >= "\x80" && $c3 <= "\xBF") { // yeah, almost sure it's UTF8 already
11338 15
                        $buf .= $c1 . $c2 . $c3;
11339 15
                        $i += 2;
11340
                    } else { // not valid UTF8 - convert it
11341 33
                        $buf .= self::to_utf8_convert_helper($c1);
11342
                    }
11343 26
                } elseif ($c1 >= "\xF0" && $c1 <= "\xF7") { // looks like 4 bytes UTF8
11344
11345 26
                    $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
11346 26
                    $c3 = $i + 2 >= $max ? "\x00" : $str[$i + 2];
11347 26
                    $c4 = $i + 3 >= $max ? "\x00" : $str[$i + 3];
11348
11349 26
                    if ($c2 >= "\x80" && $c2 <= "\xBF" && $c3 >= "\x80" && $c3 <= "\xBF" && $c4 >= "\x80" && $c4 <= "\xBF") { // yeah, almost sure it's UTF8 already
11350 8
                        $buf .= $c1 . $c2 . $c3 . $c4;
11351 8
                        $i += 3;
11352
                    } else { // not valid UTF8 - convert it
11353 26
                        $buf .= self::to_utf8_convert_helper($c1);
11354
                    }
11355
                } else { // doesn't look like UTF8, but should be converted
11356
11357 37
                    $buf .= self::to_utf8_convert_helper($c1);
11358
                }
11359 38
            } elseif (($c1 & "\xC0") === "\x80") { // needs conversion
11360
11361 4
                $buf .= self::to_utf8_convert_helper($c1);
11362
            } else { // it doesn't need conversion
11363
11364 38
                $buf .= $c1;
11365
            }
11366
        }
11367
11368
        // decode unicode escape sequences + unicode surrogate pairs
11369 41
        $buf = \preg_replace_callback(
11370 41
            '/\\\\u([dD][89abAB][0-9a-fA-F]{2})\\\\u([dD][cdefCDEF][\da-fA-F]{2})|\\\\u([0-9a-fA-F]{4})/',
11371
            /**
11372
             * @param array $matches
11373
             *
11374
             * @return string
11375
             */
11376
            static function (array $matches): string {
11377 12
                if (isset($matches[3])) {
11378 12
                    $cp = (int) \hexdec($matches[3]);
11379
                } else {
11380
                    // http://unicode.org/faq/utf_bom.html#utf16-4
11381
                    $cp = ((int) \hexdec($matches[1]) << 10)
11382
                          + (int) \hexdec($matches[2])
11383
                          + 0x10000
11384
                          - (0xD800 << 10)
11385
                          - 0xDC00;
11386
                }
11387
11388
                // https://github.com/php/php-src/blob/php-7.3.2/ext/standard/html.c#L471
11389
                //
11390
                // php_utf32_utf8(unsigned char *buf, unsigned k)
11391
11392 12
                if ($cp < 0x80) {
11393 8
                    return (string) self::chr($cp);
11394
                }
11395
11396 9
                if ($cp < 0xA0) {
11397
                    /** @noinspection UnnecessaryCastingInspection */
11398
                    return (string) self::chr(0xC0 | $cp >> 6) . (string) self::chr(0x80 | $cp & 0x3F);
11399
                }
11400
11401 9
                return self::decimal_to_chr($cp);
11402 41
            },
11403 41
            $buf
11404
        );
11405
11406 41
        if ($buf === null) {
11407
            return '';
11408
        }
11409
11410
        // decode UTF-8 codepoints
11411 41
        if ($decode_html_entity_to_utf8 === true) {
11412 2
            $buf = self::html_entity_decode($buf);
11413
        }
11414
11415 41
        return $buf;
11416
    }
11417
11418
    /**
11419
     * Strip whitespace or other characters from the beginning and end of a UTF-8 string.
11420
     *
11421
     * INFO: This is slower then "trim()"
11422
     *
11423
     * We can only use the original-function, if we use <= 7-Bit in the string / chars
11424
     * but the check for ASCII (7-Bit) cost more time, then we can safe here.
11425
     *
11426
     * @param string      $str   <p>The string to be trimmed</p>
11427
     * @param string|null $chars [optional] <p>Optional characters to be stripped</p>
11428
     *
11429
     * @return string the trimmed string
11430
     */
11431 55
    public static function trim(string $str = '', string $chars = null): string
11432
    {
11433 55
        if ($str === '') {
11434 9
            return '';
11435
        }
11436
11437 48
        if ($chars) {
11438 27
            $chars = \preg_quote($chars, '/');
11439 27
            $pattern = "^[${chars}]+|[${chars}]+\$";
11440
        } else {
11441 21
            $pattern = '^[\\s]+|[\\s]+$';
11442
        }
11443
11444 48
        if (self::$SUPPORT['mbstring'] === true) {
11445
            /** @noinspection PhpComposerExtensionStubsInspection */
11446 48
            return (string) \mb_ereg_replace($pattern, '', $str);
11447
        }
11448
11449 8
        return self::regex_replace($str, $pattern, '', '', '/');
11450
    }
11451
11452
    /**
11453
     * Makes string's first char uppercase.
11454
     *
11455
     * @param string      $str                           <p>The input string.</p>
11456
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
11457
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
11458
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt, tr</p>
11459
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
11460
     *
11461
     * @return string the resulting string
11462
     */
11463 69
    public static function ucfirst(
11464
        string $str,
11465
        string $encoding = 'UTF-8',
11466
        bool $clean_utf8 = false,
11467
        string $lang = null,
11468
        bool $try_to_keep_the_string_length = false
11469
    ): string {
11470 69
        if ($str === '') {
11471 3
            return '';
11472
        }
11473
11474 68
        if ($clean_utf8 === true) {
11475
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11476
            // if invalid characters are found in $haystack before $needle
11477 1
            $str = self::clean($str);
11478
        }
11479
11480 68
        $use_mb_functions = $lang === null && $try_to_keep_the_string_length === false;
11481
11482 68
        if ($encoding === 'UTF-8') {
11483 22
            $str_part_two = (string) \mb_substr($str, 1);
11484
11485 22
            if ($use_mb_functions === true) {
11486 22
                $str_part_one = \mb_strtoupper(
11487 22
                    (string) \mb_substr($str, 0, 1)
11488
                );
11489
            } else {
11490
                $str_part_one = self::strtoupper(
11491
                    (string) \mb_substr($str, 0, 1),
11492
                    $encoding,
11493
                    false,
11494
                    $lang,
11495 22
                    $try_to_keep_the_string_length
11496
                );
11497
            }
11498
        } else {
11499 47
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11500
11501 47
            $str_part_two = (string) self::substr($str, 1, null, $encoding);
11502
11503 47
            if ($use_mb_functions === true) {
11504 47
                $str_part_one = \mb_strtoupper(
11505 47
                    (string) \mb_substr($str, 0, 1, $encoding),
11506 47
                    $encoding
11507
                );
11508
            } else {
11509
                $str_part_one = self::strtoupper(
11510
                    (string) self::substr($str, 0, 1, $encoding),
11511
                    $encoding,
11512
                    false,
11513
                    $lang,
11514
                    $try_to_keep_the_string_length
11515
                );
11516
            }
11517
        }
11518
11519 68
        return $str_part_one . $str_part_two;
11520
    }
11521
11522
    /**
11523
     * alias for "UTF8::ucfirst()"
11524
     *
11525
     * @param string $str
11526
     * @param string $encoding
11527
     * @param bool   $clean_utf8
11528
     *
11529
     * @return string
11530
     *
11531
     * @see UTF8::ucfirst()
11532
     * @deprecated <p>please use "UTF8::ucfirst()"</p>
11533
     */
11534 1
    public static function ucword(
11535
        string $str,
11536
        string $encoding = 'UTF-8',
11537
        bool $clean_utf8 = false
11538
    ): string {
11539 1
        return self::ucfirst($str, $encoding, $clean_utf8);
11540
    }
11541
11542
    /**
11543
     * Uppercase for all words in the string.
11544
     *
11545
     * @param string   $str        <p>The input string.</p>
11546
     * @param string[] $exceptions [optional] <p>Exclusion for some words.</p>
11547
     * @param string   $char_list  [optional] <p>Additional chars that contains to words and do not start a new
11548
     *                             word.</p>
11549
     * @param string   $encoding   [optional] <p>Set the charset.</p>
11550
     * @param bool     $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
11551
     *
11552
     * @return string
11553
     */
11554 8
    public static function ucwords(
11555
        string $str,
11556
        array $exceptions = [],
11557
        string $char_list = '',
11558
        string $encoding = 'UTF-8',
11559
        bool $clean_utf8 = false
11560
    ): string {
11561 8
        if (!$str) {
11562 2
            return '';
11563
        }
11564
11565
        // INFO: mb_convert_case($str, MB_CASE_TITLE);
11566
        // -> MB_CASE_TITLE didn't only uppercase the first letter, it also lowercase all other letters
11567
11568 7
        if ($clean_utf8 === true) {
11569
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11570
            // if invalid characters are found in $haystack before $needle
11571 1
            $str = self::clean($str);
11572
        }
11573
11574 7
        $use_php_default_functions = !(bool) ($char_list . \implode('', $exceptions));
11575
11576
        if (
11577 7
            $use_php_default_functions === true
11578
            &&
11579 7
            ASCII::is_ascii($str) === true
11580
        ) {
11581
            return \ucwords($str);
11582
        }
11583
11584 7
        $words = self::str_to_words($str, $char_list);
11585 7
        $use_exceptions = \count($exceptions) > 0;
11586
11587 7
        foreach ($words as &$word) {
11588 7
            if (!$word) {
11589 7
                continue;
11590
            }
11591
11592
            if (
11593 7
                $use_exceptions === false
11594
                ||
11595 7
                !\in_array($word, $exceptions, true)
11596
            ) {
11597 7
                $word = self::ucfirst($word, $encoding);
11598
            }
11599
        }
11600
11601 7
        return \implode('', $words);
11602
    }
11603
11604
    /**
11605
     * Multi decode HTML entity + fix urlencoded-win1252-chars.
11606
     *
11607
     * e.g:
11608
     * 'test+test'                     => 'test test'
11609
     * 'D&#252;sseldorf'               => 'Düsseldorf'
11610
     * 'D%FCsseldorf'                  => 'Düsseldorf'
11611
     * 'D&#xFC;sseldorf'               => 'Düsseldorf'
11612
     * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
11613
     * 'Düsseldorf'                   => 'Düsseldorf'
11614
     * 'D%C3%BCsseldorf'               => 'Düsseldorf'
11615
     * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
11616
     * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
11617
     *
11618
     * @param string $str          <p>The input string.</p>
11619
     * @param bool   $multi_decode <p>Decode as often as possible.</p>
11620
     *
11621
     * @return string
11622
     */
11623 4
    public static function urldecode(string $str, bool $multi_decode = true): string
11624
    {
11625 4
        if ($str === '') {
11626 3
            return '';
11627
        }
11628
11629
        if (
11630 4
            \strpos($str, '&') === false
11631
            &&
11632 4
            \strpos($str, '%') === false
11633
            &&
11634 4
            \strpos($str, '+') === false
11635
            &&
11636 4
            \strpos($str, '\u') === false
11637
        ) {
11638 3
            return self::fix_simple_utf8($str);
11639
        }
11640
11641 4
        $str = self::urldecode_unicode_helper($str);
11642
11643
        do {
11644 4
            $str_compare = $str;
11645
11646
            /**
11647
             * @psalm-suppress PossiblyInvalidArgument
11648
             */
11649 4
            $str = self::fix_simple_utf8(
11650 4
                \urldecode(
11651 4
                    self::html_entity_decode(
11652 4
                        self::to_utf8($str),
11653 4
                        \ENT_QUOTES | \ENT_HTML5
11654
                    )
11655
                )
11656
            );
11657 4
        } while ($multi_decode === true && $str_compare !== $str);
11658
11659 4
        return $str;
11660
    }
11661
11662
    /**
11663
     * Return a array with "urlencoded"-win1252 -> UTF-8
11664
     *
11665
     * @return string[]
11666
     *
11667
     * @deprecated <p>please use the "UTF8::urldecode()" function to decode a string</p>
11668
     */
11669 2
    public static function urldecode_fix_win1252_chars(): array
11670
    {
11671
        return [
11672 2
            '%20' => ' ',
11673
            '%21' => '!',
11674
            '%22' => '"',
11675
            '%23' => '#',
11676
            '%24' => '$',
11677
            '%25' => '%',
11678
            '%26' => '&',
11679
            '%27' => "'",
11680
            '%28' => '(',
11681
            '%29' => ')',
11682
            '%2A' => '*',
11683
            '%2B' => '+',
11684
            '%2C' => ',',
11685
            '%2D' => '-',
11686
            '%2E' => '.',
11687
            '%2F' => '/',
11688
            '%30' => '0',
11689
            '%31' => '1',
11690
            '%32' => '2',
11691
            '%33' => '3',
11692
            '%34' => '4',
11693
            '%35' => '5',
11694
            '%36' => '6',
11695
            '%37' => '7',
11696
            '%38' => '8',
11697
            '%39' => '9',
11698
            '%3A' => ':',
11699
            '%3B' => ';',
11700
            '%3C' => '<',
11701
            '%3D' => '=',
11702
            '%3E' => '>',
11703
            '%3F' => '?',
11704
            '%40' => '@',
11705
            '%41' => 'A',
11706
            '%42' => 'B',
11707
            '%43' => 'C',
11708
            '%44' => 'D',
11709
            '%45' => 'E',
11710
            '%46' => 'F',
11711
            '%47' => 'G',
11712
            '%48' => 'H',
11713
            '%49' => 'I',
11714
            '%4A' => 'J',
11715
            '%4B' => 'K',
11716
            '%4C' => 'L',
11717
            '%4D' => 'M',
11718
            '%4E' => 'N',
11719
            '%4F' => 'O',
11720
            '%50' => 'P',
11721
            '%51' => 'Q',
11722
            '%52' => 'R',
11723
            '%53' => 'S',
11724
            '%54' => 'T',
11725
            '%55' => 'U',
11726
            '%56' => 'V',
11727
            '%57' => 'W',
11728
            '%58' => 'X',
11729
            '%59' => 'Y',
11730
            '%5A' => 'Z',
11731
            '%5B' => '[',
11732
            '%5C' => '\\',
11733
            '%5D' => ']',
11734
            '%5E' => '^',
11735
            '%5F' => '_',
11736
            '%60' => '`',
11737
            '%61' => 'a',
11738
            '%62' => 'b',
11739
            '%63' => 'c',
11740
            '%64' => 'd',
11741
            '%65' => 'e',
11742
            '%66' => 'f',
11743
            '%67' => 'g',
11744
            '%68' => 'h',
11745
            '%69' => 'i',
11746
            '%6A' => 'j',
11747
            '%6B' => 'k',
11748
            '%6C' => 'l',
11749
            '%6D' => 'm',
11750
            '%6E' => 'n',
11751
            '%6F' => 'o',
11752
            '%70' => 'p',
11753
            '%71' => 'q',
11754
            '%72' => 'r',
11755
            '%73' => 's',
11756
            '%74' => 't',
11757
            '%75' => 'u',
11758
            '%76' => 'v',
11759
            '%77' => 'w',
11760
            '%78' => 'x',
11761
            '%79' => 'y',
11762
            '%7A' => 'z',
11763
            '%7B' => '{',
11764
            '%7C' => '|',
11765
            '%7D' => '}',
11766
            '%7E' => '~',
11767
            '%7F' => '',
11768
            '%80' => '`',
11769
            '%81' => '',
11770
            '%82' => '‚',
11771
            '%83' => 'ƒ',
11772
            '%84' => '„',
11773
            '%85' => '…',
11774
            '%86' => '†',
11775
            '%87' => '‡',
11776
            '%88' => 'ˆ',
11777
            '%89' => '‰',
11778
            '%8A' => 'Š',
11779
            '%8B' => '‹',
11780
            '%8C' => 'Œ',
11781
            '%8D' => '',
11782
            '%8E' => 'Ž',
11783
            '%8F' => '',
11784
            '%90' => '',
11785
            '%91' => '‘',
11786
            '%92' => '’',
11787
            '%93' => '“',
11788
            '%94' => '”',
11789
            '%95' => '•',
11790
            '%96' => '–',
11791
            '%97' => '—',
11792
            '%98' => '˜',
11793
            '%99' => '™',
11794
            '%9A' => 'š',
11795
            '%9B' => '›',
11796
            '%9C' => 'œ',
11797
            '%9D' => '',
11798
            '%9E' => 'ž',
11799
            '%9F' => 'Ÿ',
11800
            '%A0' => '',
11801
            '%A1' => '¡',
11802
            '%A2' => '¢',
11803
            '%A3' => '£',
11804
            '%A4' => '¤',
11805
            '%A5' => '¥',
11806
            '%A6' => '¦',
11807
            '%A7' => '§',
11808
            '%A8' => '¨',
11809
            '%A9' => '©',
11810
            '%AA' => 'ª',
11811
            '%AB' => '«',
11812
            '%AC' => '¬',
11813
            '%AD' => '',
11814
            '%AE' => '®',
11815
            '%AF' => '¯',
11816
            '%B0' => '°',
11817
            '%B1' => '±',
11818
            '%B2' => '²',
11819
            '%B3' => '³',
11820
            '%B4' => '´',
11821
            '%B5' => 'µ',
11822
            '%B6' => '¶',
11823
            '%B7' => '·',
11824
            '%B8' => '¸',
11825
            '%B9' => '¹',
11826
            '%BA' => 'º',
11827
            '%BB' => '»',
11828
            '%BC' => '¼',
11829
            '%BD' => '½',
11830
            '%BE' => '¾',
11831
            '%BF' => '¿',
11832
            '%C0' => 'À',
11833
            '%C1' => 'Á',
11834
            '%C2' => 'Â',
11835
            '%C3' => 'Ã',
11836
            '%C4' => 'Ä',
11837
            '%C5' => 'Å',
11838
            '%C6' => 'Æ',
11839
            '%C7' => 'Ç',
11840
            '%C8' => 'È',
11841
            '%C9' => 'É',
11842
            '%CA' => 'Ê',
11843
            '%CB' => 'Ë',
11844
            '%CC' => 'Ì',
11845
            '%CD' => 'Í',
11846
            '%CE' => 'Î',
11847
            '%CF' => 'Ï',
11848
            '%D0' => 'Ð',
11849
            '%D1' => 'Ñ',
11850
            '%D2' => 'Ò',
11851
            '%D3' => 'Ó',
11852
            '%D4' => 'Ô',
11853
            '%D5' => 'Õ',
11854
            '%D6' => 'Ö',
11855
            '%D7' => '×',
11856
            '%D8' => 'Ø',
11857
            '%D9' => 'Ù',
11858
            '%DA' => 'Ú',
11859
            '%DB' => 'Û',
11860
            '%DC' => 'Ü',
11861
            '%DD' => 'Ý',
11862
            '%DE' => 'Þ',
11863
            '%DF' => 'ß',
11864
            '%E0' => 'à',
11865
            '%E1' => 'á',
11866
            '%E2' => 'â',
11867
            '%E3' => 'ã',
11868
            '%E4' => 'ä',
11869
            '%E5' => 'å',
11870
            '%E6' => 'æ',
11871
            '%E7' => 'ç',
11872
            '%E8' => 'è',
11873
            '%E9' => 'é',
11874
            '%EA' => 'ê',
11875
            '%EB' => 'ë',
11876
            '%EC' => 'ì',
11877
            '%ED' => 'í',
11878
            '%EE' => 'î',
11879
            '%EF' => 'ï',
11880
            '%F0' => 'ð',
11881
            '%F1' => 'ñ',
11882
            '%F2' => 'ò',
11883
            '%F3' => 'ó',
11884
            '%F4' => 'ô',
11885
            '%F5' => 'õ',
11886
            '%F6' => 'ö',
11887
            '%F7' => '÷',
11888
            '%F8' => 'ø',
11889
            '%F9' => 'ù',
11890
            '%FA' => 'ú',
11891
            '%FB' => 'û',
11892
            '%FC' => 'ü',
11893
            '%FD' => 'ý',
11894
            '%FE' => 'þ',
11895
            '%FF' => 'ÿ',
11896
        ];
11897
    }
11898
11899
    /**
11900
     * Decodes a UTF-8 string to ISO-8859-1.
11901
     *
11902
     * @param string $str             <p>The input string.</p>
11903
     * @param bool   $keep_utf8_chars
11904
     *
11905
     * @return string
11906
     */
11907 14
    public static function utf8_decode(string $str, bool $keep_utf8_chars = false): string
11908
    {
11909 14
        if ($str === '') {
11910 6
            return '';
11911
        }
11912
11913
        // save for later comparision
11914 14
        $str_backup = $str;
11915 14
        $len = \strlen($str);
11916
11917 14
        if (self::$ORD === null) {
11918
            self::$ORD = self::getData('ord');
11919
        }
11920
11921 14
        if (self::$CHR === null) {
11922
            self::$CHR = self::getData('chr');
11923
        }
11924
11925 14
        $no_char_found = '?';
11926
        /** @noinspection ForeachInvariantsInspection */
11927 14
        for ($i = 0, $j = 0; $i < $len; ++$i, ++$j) {
11928 14
            switch ($str[$i] & "\xF0") {
11929 14
                case "\xC0":
11930 13
                case "\xD0":
11931 13
                    $c = (self::$ORD[$str[$i] & "\x1F"] << 6) | self::$ORD[$str[++$i] & "\x3F"];
11932 13
                    $str[$j] = $c < 256 ? self::$CHR[$c] : $no_char_found;
11933
11934 13
                    break;
11935
11936
                /** @noinspection PhpMissingBreakStatementInspection */
11937 13
                case "\xF0":
11938
                    ++$i;
11939
11940
                // no break
11941
11942 13
                case "\xE0":
11943 11
                    $str[$j] = $no_char_found;
11944 11
                    $i += 2;
11945
11946 11
                    break;
11947
11948
                default:
11949 12
                    $str[$j] = $str[$i];
11950
            }
11951
        }
11952
11953
        /** @var string|false $return - needed for PhpStan (stubs error) */
11954 14
        $return = \substr($str, 0, $j);
11955 14
        if ($return === false) {
11956
            $return = '';
11957
        }
11958
11959
        if (
11960 14
            $keep_utf8_chars === true
11961
            &&
11962 14
            (int) self::strlen($return) >= (int) self::strlen($str_backup)
11963
        ) {
11964 2
            return $str_backup;
11965
        }
11966
11967 14
        return $return;
11968
    }
11969
11970
    /**
11971
     * Encodes an ISO-8859-1 string to UTF-8.
11972
     *
11973
     * @param string $str <p>The input string.</p>
11974
     *
11975
     * @return string
11976
     */
11977 14
    public static function utf8_encode(string $str): string
11978
    {
11979 14
        if ($str === '') {
11980 14
            return '';
11981
        }
11982
11983
        /** @var string|false $str - the polyfill maybe return false */
11984 14
        $str = \utf8_encode($str);
0 ignored issues
show
Bug introduced by
It seems like $str can also be of type false; however, parameter $data of utf8_encode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

11984
        $str = \utf8_encode(/** @scrutinizer ignore-type */ $str);
Loading history...
11985
11986
        /** @noinspection CallableParameterUseCaseInTypeContextInspection */
11987
        /** @psalm-suppress TypeDoesNotContainType */
11988 14
        if ($str === false) {
11989
            return '';
11990
        }
11991
11992 14
        return $str;
11993
    }
11994
11995
    /**
11996
     * fix -> utf8-win1252 chars
11997
     *
11998
     * @param string $str <p>The input string.</p>
11999
     *
12000
     * @return string
12001
     *
12002
     * @deprecated <p>please use "UTF8::fix_simple_utf8()"</p>
12003
     */
12004 2
    public static function utf8_fix_win1252_chars(string $str): string
12005
    {
12006 2
        return self::fix_simple_utf8($str);
12007
    }
12008
12009
    /**
12010
     * Returns an array with all utf8 whitespace characters.
12011
     *
12012
     * @see http://www.bogofilter.org/pipermail/bogofilter/2003-March/001889.html
12013
     *
12014
     * @return string[]
12015
     *                  An array with all known whitespace characters as values and the type of whitespace as keys
12016
     *                  as defined in above URL
12017
     */
12018 2
    public static function whitespace_table(): array
12019
    {
12020 2
        return self::$WHITESPACE_TABLE;
12021
    }
12022
12023
    /**
12024
     * Limit the number of words in a string.
12025
     *
12026
     * @param string $str        <p>The input string.</p>
12027
     * @param int    $limit      <p>The limit of words as integer.</p>
12028
     * @param string $str_add_on <p>Replacement for the striped string.</p>
12029
     *
12030
     * @return string
12031
     */
12032 2
    public static function words_limit(
12033
        string $str,
12034
        int $limit = 100,
12035
        string $str_add_on = '…'
12036
    ): string {
12037 2
        if ($str === '' || $limit < 1) {
12038 2
            return '';
12039
        }
12040
12041 2
        \preg_match('/^\\s*+(?:[^\\s]++\\s*+){1,' . $limit . '}/u', $str, $matches);
12042
12043
        if (
12044 2
            !isset($matches[0])
12045
            ||
12046 2
            \mb_strlen($str) === (int) \mb_strlen($matches[0])
12047
        ) {
12048 2
            return $str;
12049
        }
12050
12051 2
        return \rtrim($matches[0]) . $str_add_on;
12052
    }
12053
12054
    /**
12055
     * Wraps a string to a given number of characters
12056
     *
12057
     * @see http://php.net/manual/en/function.wordwrap.php
12058
     *
12059
     * @param string $str   <p>The input string.</p>
12060
     * @param int    $width [optional] <p>The column width.</p>
12061
     * @param string $break [optional] <p>The line is broken using the optional break parameter.</p>
12062
     * @param bool   $cut   [optional] <p>
12063
     *                      If the cut is set to true, the string is
12064
     *                      always wrapped at or before the specified width. So if you have
12065
     *                      a word that is larger than the given width, it is broken apart.
12066
     *                      </p>
12067
     *
12068
     * @return string
12069
     *                <p>The given string wrapped at the specified column.</p>
12070
     */
12071 12
    public static function wordwrap(
12072
        string $str,
12073
        int $width = 75,
12074
        string $break = "\n",
12075
        bool $cut = false
12076
    ): string {
12077 12
        if ($str === '' || $break === '') {
12078 4
            return '';
12079
        }
12080
12081 10
        $str_split = \explode($break, $str);
12082 10
        if ($str_split === false) {
12083
            return '';
12084
        }
12085
12086 10
        $chars = [];
12087 10
        $word_split = '';
12088 10
        foreach ($str_split as $i => $i_value) {
12089 10
            if ($i) {
12090 3
                $chars[] = $break;
12091 3
                $word_split .= '#';
12092
            }
12093
12094 10
            foreach (self::str_split($i_value) as $c) {
12095 10
                $chars[] = $c;
12096 10
                if ($c === ' ') {
12097 3
                    $word_split .= ' ';
12098
                } else {
12099 10
                    $word_split .= '?';
12100
                }
12101
            }
12102
        }
12103
12104 10
        $str_return = '';
12105 10
        $j = 0;
12106 10
        $b = -1;
12107 10
        $i = -1;
12108 10
        $word_split = \wordwrap($word_split, $width, '#', $cut);
12109
12110 10
        $max = \mb_strlen($word_split);
12111 10
        while (($b = \mb_strpos($word_split, '#', $b + 1)) !== false) {
12112 8
            for (++$i; $i < $b; ++$i) {
12113 8
                $str_return .= $chars[$j];
12114 8
                unset($chars[$j++]);
12115
12116
                // prevent endless loop, e.g. if there is a error in the "mb_*" polyfill
12117 8
                if ($i > $max) {
12118
                    break 2;
12119
                }
12120
            }
12121
12122
            if (
12123 8
                $break === $chars[$j]
12124
                ||
12125 8
                $chars[$j] === ' '
12126
            ) {
12127 5
                unset($chars[$j++]);
12128
            }
12129
12130 8
            $str_return .= $break;
12131
12132
            // prevent endless loop, e.g. if there is a error in the "mb_*" polyfill
12133 8
            if ($b > $max) {
12134
                break;
12135
            }
12136
        }
12137
12138 10
        return $str_return . \implode('', $chars);
12139
    }
12140
12141
    /**
12142
     * Line-Wrap the string after $limit, but split the string by "$delimiter" before ...
12143
     *    ... so that we wrap the per line.
12144
     *
12145
     * @param string      $str             <p>The input string.</p>
12146
     * @param int         $width           [optional] <p>The column width.</p>
12147
     * @param string      $break           [optional] <p>The line is broken using the optional break parameter.</p>
12148
     * @param bool        $cut             [optional] <p>
12149
     *                                     If the cut is set to true, the string is
12150
     *                                     always wrapped at or before the specified width. So if you have
12151
     *                                     a word that is larger than the given width, it is broken apart.
12152
     *                                     </p>
12153
     * @param bool        $add_final_break [optional] <p>
12154
     *                                     If this flag is true, then the method will add a $break at the end
12155
     *                                     of the result string.
12156
     *                                     </p>
12157
     * @param string|null $delimiter       [optional] <p>
12158
     *                                     You can change the default behavior, where we split the string by newline.
12159
     *                                     </p>
12160
     *
12161
     * @return string
12162
     */
12163 1
    public static function wordwrap_per_line(
12164
        string $str,
12165
        int $width = 75,
12166
        string $break = "\n",
12167
        bool $cut = false,
12168
        bool $add_final_break = true,
12169
        string $delimiter = null
12170
    ): string {
12171 1
        if ($delimiter === null) {
12172 1
            $strings = \preg_split('/\\r\\n|\\r|\\n/', $str);
12173
        } else {
12174 1
            $strings = \explode($delimiter, $str);
12175
        }
12176
12177 1
        $string_helper_array = [];
12178 1
        if ($strings !== false) {
12179 1
            foreach ($strings as $value) {
12180 1
                $string_helper_array[] = self::wordwrap($value, $width, $break, $cut);
12181
            }
12182
        }
12183
12184 1
        if ($add_final_break) {
12185 1
            $final_break = $break;
12186
        } else {
12187 1
            $final_break = '';
12188
        }
12189
12190 1
        return \implode($delimiter ?? "\n", $string_helper_array) . $final_break;
12191
    }
12192
12193
    /**
12194
     * Returns an array of Unicode White Space characters.
12195
     *
12196
     * @return string[] an array with numeric code point as key and White Space Character as value
12197
     */
12198 2
    public static function ws(): array
12199
    {
12200 2
        return self::$WHITESPACE;
12201
    }
12202
12203
    /**
12204
     * @param string $str
12205
     * @param string $encoding
12206
     *
12207
     * @return string
12208
     */
12209
    private static function html_entity_decode_helper(string $str, string $encoding): string
12210
    {
12211
        return (string) \preg_replace_callback(
12212
            "/&#\d{2,6};/",
12213
            /**
12214
             * @param string[] $matches
12215
             *
12216
             * @return string
12217
             */
12218
            static function (array $matches) use ($encoding): string {
12219
                $return_tmp = \mb_convert_encoding($matches[0], $encoding, 'HTML-ENTITIES');
12220
                if ($return_tmp !== '"' && $return_tmp !== "'") {
12221
                    return $return_tmp;
12222
                }
12223
12224
                return $matches[0];
12225
            },
12226
            $str
12227
        );
12228
    }
12229
12230
    /**
12231
     * Checks whether the passed string contains only byte sequences that are valid UTF-8 characters.
12232
     *
12233
     * @see http://hsivonen.iki.fi/php-utf8/
12234
     *
12235
     * @param string $str    <p>The string to be checked.</p>
12236
     * @param bool   $strict <p>Check also if the string is not UTF-16 or UTF-32.</p>
12237
     *
12238
     * @return bool
12239
     */
12240 108
    private static function is_utf8_string(string $str, bool $strict = false): bool
12241
    {
12242 108
        if ($str === '') {
12243 14
            return true;
12244
        }
12245
12246 102
        if ($strict === true) {
12247 2
            $is_binary = self::is_binary($str, true);
12248
12249 2
            if ($is_binary && self::is_utf16($str, false) !== false) {
12250 2
                return false;
12251
            }
12252
12253
            if ($is_binary && self::is_utf32($str, false) !== false) {
12254
                return false;
12255
            }
12256
        }
12257
12258 102
        if (self::pcre_utf8_support() !== true) {
12259
            // If even just the first character can be matched, when the /u
12260
            // modifier is used, then it's valid UTF-8. If the UTF-8 is somehow
12261
            // invalid, nothing at all will match, even if the string contains
12262
            // some valid sequences
12263
            return \preg_match('/^./us', $str, $ar) === 1;
12264
        }
12265
12266 102
        $mState = 0; // cached expected number of octets after the current octet
12267
        // until the beginning of the next UTF8 character sequence
12268 102
        $mUcs4 = 0; // cached Unicode character
12269 102
        $mBytes = 1; // cached expected number of octets in the current sequence
12270
12271 102
        if (self::$ORD === null) {
12272
            self::$ORD = self::getData('ord');
12273
        }
12274
12275 102
        $len = \strlen($str);
12276
        /** @noinspection ForeachInvariantsInspection */
12277 102
        for ($i = 0; $i < $len; ++$i) {
12278 102
            $in = self::$ORD[$str[$i]];
12279
12280 102
            if ($mState === 0) {
12281
                // When mState is zero we expect either a US-ASCII character or a
12282
                // multi-octet sequence.
12283 102
                if ((0x80 & $in) === 0) {
12284
                    // US-ASCII, pass straight through.
12285 97
                    $mBytes = 1;
12286 83
                } elseif ((0xE0 & $in) === 0xC0) {
12287
                    // First octet of 2 octet sequence.
12288 73
                    $mUcs4 = $in;
12289 73
                    $mUcs4 = ($mUcs4 & 0x1F) << 6;
12290 73
                    $mState = 1;
12291 73
                    $mBytes = 2;
12292 58
                } elseif ((0xF0 & $in) === 0xE0) {
12293
                    // First octet of 3 octet sequence.
12294 42
                    $mUcs4 = $in;
12295 42
                    $mUcs4 = ($mUcs4 & 0x0F) << 12;
12296 42
                    $mState = 2;
12297 42
                    $mBytes = 3;
12298 29
                } elseif ((0xF8 & $in) === 0xF0) {
12299
                    // First octet of 4 octet sequence.
12300 18
                    $mUcs4 = $in;
12301 18
                    $mUcs4 = ($mUcs4 & 0x07) << 18;
12302 18
                    $mState = 3;
12303 18
                    $mBytes = 4;
12304 13
                } elseif ((0xFC & $in) === 0xF8) {
12305
                    /* First octet of 5 octet sequence.
12306
                     *
12307
                     * This is illegal because the encoded codepoint must be either
12308
                     * (a) not the shortest form or
12309
                     * (b) outside the Unicode range of 0-0x10FFFF.
12310
                     * Rather than trying to resynchronize, we will carry on until the end
12311
                     * of the sequence and let the later error handling code catch it.
12312
                     */
12313 5
                    $mUcs4 = $in;
12314 5
                    $mUcs4 = ($mUcs4 & 0x03) << 24;
12315 5
                    $mState = 4;
12316 5
                    $mBytes = 5;
12317 10
                } elseif ((0xFE & $in) === 0xFC) {
12318
                    // First octet of 6 octet sequence, see comments for 5 octet sequence.
12319 5
                    $mUcs4 = $in;
12320 5
                    $mUcs4 = ($mUcs4 & 1) << 30;
12321 5
                    $mState = 5;
12322 5
                    $mBytes = 6;
12323
                } else {
12324
                    // Current octet is neither in the US-ASCII range nor a legal first
12325
                    // octet of a multi-octet sequence.
12326 102
                    return false;
12327
                }
12328 83
            } elseif ((0xC0 & $in) === 0x80) {
12329
12330
                // When mState is non-zero, we expect a continuation of the multi-octet
12331
                // sequence
12332
12333
                // Legal continuation.
12334 75
                $shift = ($mState - 1) * 6;
12335 75
                $tmp = $in;
12336 75
                $tmp = ($tmp & 0x0000003F) << $shift;
12337 75
                $mUcs4 |= $tmp;
12338
                // Prefix: End of the multi-octet sequence. mUcs4 now contains the final
12339
                // Unicode code point to be output.
12340 75
                if (--$mState === 0) {
12341
                    // Check for illegal sequences and code points.
12342
                    //
12343
                    // From Unicode 3.1, non-shortest form is illegal
12344
                    if (
12345 75
                        ($mBytes === 2 && $mUcs4 < 0x0080)
12346
                        ||
12347 75
                        ($mBytes === 3 && $mUcs4 < 0x0800)
12348
                        ||
12349 75
                        ($mBytes === 4 && $mUcs4 < 0x10000)
12350
                        ||
12351 75
                        ($mBytes > 4)
12352
                        ||
12353
                        // From Unicode 3.2, surrogate characters are illegal.
12354 75
                        (($mUcs4 & 0xFFFFF800) === 0xD800)
12355
                        ||
12356
                        // Code points outside the Unicode range are illegal.
12357 75
                        ($mUcs4 > 0x10FFFF)
12358
                    ) {
12359 8
                        return false;
12360
                    }
12361
                    // initialize UTF8 cache
12362 75
                    $mState = 0;
12363 75
                    $mUcs4 = 0;
12364 75
                    $mBytes = 1;
12365
                }
12366
            } else {
12367
                // ((0xC0 & (*in) != 0x80) && (mState != 0))
12368
                // Incomplete multi-octet sequence.
12369 35
                return false;
12370
            }
12371
        }
12372
12373 67
        return true;
12374
    }
12375
12376
    /**
12377
     * @param string $str
12378
     * @param bool   $use_lowercase      <p>Use uppercase by default, otherwise use lowercase.</p>
12379
     * @param bool   $use_full_case_fold <p>Convert not only common cases.</p>
12380
     *
12381
     * @return string
12382
     */
12383 33
    private static function fixStrCaseHelper(
12384
        string $str,
12385
        $use_lowercase = false,
12386
        $use_full_case_fold = false
12387
    ): string {
12388 33
        $upper = self::$COMMON_CASE_FOLD['upper'];
12389 33
        $lower = self::$COMMON_CASE_FOLD['lower'];
12390
12391 33
        if ($use_lowercase === true) {
12392 2
            $str = \str_replace(
12393 2
                $upper,
12394 2
                $lower,
12395 2
                $str
12396
            );
12397
        } else {
12398 31
            $str = \str_replace(
12399 31
                $lower,
12400 31
                $upper,
12401 31
                $str
12402
            );
12403
        }
12404
12405 33
        if ($use_full_case_fold) {
12406 31
            static $FULL_CASE_FOLD = null;
12407 31
            if ($FULL_CASE_FOLD === null) {
12408 1
                $FULL_CASE_FOLD = self::getData('caseFolding_full');
12409
            }
12410
12411 31
            if ($use_lowercase === true) {
12412 2
                $str = \str_replace($FULL_CASE_FOLD[0], $FULL_CASE_FOLD[1], $str);
12413
            } else {
12414 29
                $str = \str_replace($FULL_CASE_FOLD[1], $FULL_CASE_FOLD[0], $str);
12415
            }
12416
        }
12417
12418 33
        return $str;
12419
    }
12420
12421
    /**
12422
     * get data from "/data/*.php"
12423
     *
12424
     * @param string $file
12425
     *
12426
     * @return array
12427
     */
12428 6
    private static function getData(string $file): array
12429
    {
12430
        /** @noinspection PhpIncludeInspection */
12431
        /** @noinspection UsingInclusionReturnValueInspection */
12432
        /** @psalm-suppress UnresolvableInclude */
12433 6
        return include __DIR__ . '/data/' . $file . '.php';
12434
    }
12435
12436
    /**
12437
     * @return true|null
12438
     */
12439 12
    private static function initEmojiData()
12440
    {
12441 12
        if (self::$EMOJI_KEYS_CACHE === null) {
12442 1
            if (self::$EMOJI === null) {
12443 1
                self::$EMOJI = self::getData('emoji');
12444
            }
12445
12446 1
            \uksort(
12447 1
                self::$EMOJI,
12448
                static function (string $a, string $b): int {
12449 1
                    return \strlen($b) <=> \strlen($a);
12450 1
                }
12451
            );
12452
12453 1
            self::$EMOJI_KEYS_CACHE = \array_keys(self::$EMOJI);
12454 1
            self::$EMOJI_VALUES_CACHE = \array_values(self::$EMOJI);
12455
12456 1
            foreach (self::$EMOJI_KEYS_CACHE as $key) {
12457 1
                $tmp_key = \crc32($key);
12458 1
                self::$EMOJI_KEYS_REVERSIBLE_CACHE[] = '_-_PORTABLE_UTF8_-_' . $tmp_key . '_-_' . \strrev((string) $tmp_key) . '_-_8FTU_ELBATROP_-_';
12459
            }
12460
12461 1
            return true;
12462
        }
12463
12464 12
        return null;
12465
    }
12466
12467
    /**
12468
     * Checks whether mbstring "overloaded" is active on the server.
12469
     *
12470
     * @return bool
12471
     */
12472
    private static function mbstring_overloaded(): bool
12473
    {
12474
        /**
12475
         * INI directive 'mbstring.func_overload' is deprecated since PHP 7.2
12476
         */
12477
12478
        /** @noinspection PhpComposerExtensionStubsInspection */
12479
        /** @noinspection PhpUsageOfSilenceOperatorInspection */
12480
        return \defined('MB_OVERLOAD_STRING')
12481
               &&
12482
               ((int) @\ini_get('mbstring.func_overload') & \MB_OVERLOAD_STRING);
12483
    }
12484
12485
    /**
12486
     * @param array    $strings
12487
     * @param bool     $remove_empty_values
12488
     * @param int|null $remove_short_values
12489
     *
12490
     * @return array
12491
     */
12492 2
    private static function reduce_string_array(
12493
        array $strings,
12494
        bool $remove_empty_values,
12495
        int $remove_short_values = null
12496
    ): array {
12497
        // init
12498 2
        $return = [];
12499
12500 2
        foreach ($strings as &$str) {
12501
            if (
12502 2
                $remove_short_values !== null
12503
                &&
12504 2
                \mb_strlen($str) <= $remove_short_values
12505
            ) {
12506 2
                continue;
12507
            }
12508
12509
            if (
12510 2
                $remove_empty_values === true
12511
                &&
12512 2
                \trim($str) === ''
12513
            ) {
12514 2
                continue;
12515
            }
12516
12517 2
            $return[] = $str;
12518
        }
12519
12520 2
        return $return;
12521
    }
12522
12523
    /**
12524
     * rxClass
12525
     *
12526
     * @param string $s
12527
     * @param string $class
12528
     *
12529
     * @return string
12530
     */
12531 33
    private static function rxClass(string $s, string $class = ''): string
12532
    {
12533 33
        static $RX_CLASS_CACHE = [];
12534
12535 33
        $cache_key = $s . $class;
12536
12537 33
        if (isset($RX_CLASS_CACHE[$cache_key])) {
12538 21
            return $RX_CLASS_CACHE[$cache_key];
12539
        }
12540
12541 16
        $class_array = [$class];
12542
12543
        /** @noinspection SuspiciousLoopInspection */
12544
        /** @noinspection AlterInForeachInspection */
12545 16
        foreach (self::str_split($s) as &$s) {
0 ignored issues
show
Bug introduced by
The expression self::str_split($s) cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
12546 15
            if ($s === '-') {
12547
                $class_array[0] = '-' . $class_array[0];
12548 15
            } elseif (!isset($s[2])) {
12549 15
                $class_array[0] .= \preg_quote($s, '/');
12550 1
            } elseif (self::strlen($s) === 1) {
12551 1
                $class_array[0] .= $s;
12552
            } else {
12553 15
                $class_array[] = $s;
12554
            }
12555
        }
12556
12557 16
        if ($class_array[0]) {
12558 16
            $class_array[0] = '[' . $class_array[0] . ']';
12559
        }
12560
12561 16
        if (\count($class_array) === 1) {
12562 16
            $return = $class_array[0];
12563
        } else {
12564
            $return = '(?:' . \implode('|', $class_array) . ')';
12565
        }
12566
12567 16
        $RX_CLASS_CACHE[$cache_key] = $return;
12568
12569 16
        return $return;
12570
    }
12571
12572
    /**
12573
     * Personal names such as "Marcus Aurelius" are sometimes typed incorrectly using lowercase ("marcus aurelius").
12574
     *
12575
     * @param string $names
12576
     * @param string $delimiter
12577
     * @param string $encoding
12578
     *
12579
     * @return string
12580
     */
12581 1
    private static function str_capitalize_name_helper(string $names, string $delimiter, string $encoding = 'UTF-8'): string
12582
    {
12583
        // init
12584 1
        $name_helper_array = \explode($delimiter, $names);
12585 1
        if ($name_helper_array === false) {
12586
            return '';
12587
        }
12588
12589
        $special_cases = [
12590 1
            'names' => [
12591
                'ab',
12592
                'af',
12593
                'al',
12594
                'and',
12595
                'ap',
12596
                'bint',
12597
                'binte',
12598
                'da',
12599
                'de',
12600
                'del',
12601
                'den',
12602
                'der',
12603
                'di',
12604
                'dit',
12605
                'ibn',
12606
                'la',
12607
                'mac',
12608
                'nic',
12609
                'of',
12610
                'ter',
12611
                'the',
12612
                'und',
12613
                'van',
12614
                'von',
12615
                'y',
12616
                'zu',
12617
            ],
12618
            'prefixes' => [
12619
                'al-',
12620
                "d'",
12621
                'ff',
12622
                "l'",
12623
                'mac',
12624
                'mc',
12625
                'nic',
12626
            ],
12627
        ];
12628
12629 1
        foreach ($name_helper_array as &$name) {
12630 1
            if (\in_array($name, $special_cases['names'], true)) {
12631 1
                continue;
12632
            }
12633
12634 1
            $continue = false;
12635
12636 1
            if ($delimiter === '-') {
12637
                /** @noinspection AlterInForeachInspection */
12638 1
                foreach ((array) $special_cases['names'] as &$beginning) {
12639 1
                    if (self::strpos($name, $beginning, 0, $encoding) === 0) {
12640 1
                        $continue = true;
12641
                    }
12642
                }
12643
            }
12644
12645
            /** @noinspection AlterInForeachInspection */
12646 1
            foreach ((array) $special_cases['prefixes'] as &$beginning) {
12647 1
                if (self::strpos($name, $beginning, 0, $encoding) === 0) {
12648 1
                    $continue = true;
12649
                }
12650
            }
12651
12652 1
            if ($continue === true) {
12653 1
                continue;
12654
            }
12655
12656 1
            $name = self::ucfirst($name);
12657
        }
12658
12659 1
        return \implode($delimiter, $name_helper_array);
12660
    }
12661
12662
    /**
12663
     * Generic case-sensitive transformation for collation matching.
12664
     *
12665
     * @param string $str <p>The input string</p>
12666
     *
12667
     * @return string|null
12668
     */
12669 6
    private static function strtonatfold(string $str)
12670
    {
12671
        /** @noinspection PhpUndefinedClassInspection */
12672 6
        return \preg_replace(
12673 6
            '/\p{Mn}+/u',
12674 6
            '',
12675 6
            \Normalizer::normalize($str, \Normalizer::NFD)
12676
        );
12677
    }
12678
12679
    /**
12680
     * @param int|string $input
12681
     *
12682
     * @return string
12683
     */
12684 31
    private static function to_utf8_convert_helper($input): string
12685
    {
12686
        // init
12687 31
        $buf = '';
12688
12689 31
        if (self::$ORD === null) {
12690 1
            self::$ORD = self::getData('ord');
12691
        }
12692
12693 31
        if (self::$CHR === null) {
12694 1
            self::$CHR = self::getData('chr');
12695
        }
12696
12697 31
        if (self::$WIN1252_TO_UTF8 === null) {
12698 1
            self::$WIN1252_TO_UTF8 = self::getData('win1252_to_utf8');
12699
        }
12700
12701 31
        $ordC1 = self::$ORD[$input];
12702 31
        if (isset(self::$WIN1252_TO_UTF8[$ordC1])) { // found in Windows-1252 special cases
12703 31
            $buf .= self::$WIN1252_TO_UTF8[$ordC1];
12704
        } else {
12705
            /** @noinspection OffsetOperationsInspection */
12706 1
            $cc1 = self::$CHR[$ordC1 / 64] | "\xC0";
12707 1
            $cc2 = ((string) $input & "\x3F") | "\x80";
0 ignored issues
show
Bug introduced by
Are you sure you want to use the bitwise | or did you mean ||?
Loading history...
Bug introduced by
Are you sure you want to use the bitwise & or did you mean &&?
Loading history...
12708 1
            $buf .= $cc1 . $cc2;
12709
        }
12710
12711 31
        return $buf;
12712
    }
12713
12714
    /**
12715
     * @param string $str
12716
     *
12717
     * @return string
12718
     */
12719 9
    private static function urldecode_unicode_helper(string $str): string
12720
    {
12721 9
        $pattern = '/%u([0-9a-fA-F]{3,4})/';
12722 9
        if (\preg_match($pattern, $str)) {
12723 7
            $str = (string) \preg_replace($pattern, '&#x\\1;', $str);
12724
        }
12725
12726 9
        return $str;
12727
    }
12728
}
12729