Passed
Push — master ( 362423...adaba2 )
by Lars
03:21
created

UTF8   F

Complexity

Total Complexity 1779

Size/Duplication

Total Lines 14792
Duplicated Lines 0 %

Test Coverage

Coverage 81.39%

Importance

Changes 106
Bugs 53 Features 6
Metric Value
eloc 4530
c 106
b 53
f 6
dl 0
loc 14792
ccs 3260
cts 4005
cp 0.8139
rs 0.8
wmc 1779

310 Methods

Rating   Name   Duplication   Size   Complexity  
A add_bom_to_string() 0 7 2
A array_change_key_case() 0 23 5
A __construct() 0 2 1
B between() 0 48 8
A char_at() 0 7 2
A chars() 0 4 1
A access() 0 11 4
A callback() 0 3 1
A binary_to_str() 0 12 3
A bom() 0 3 1
B chr_to_decimal() 0 38 8
A str_substr_after_first_separator() 0 28 6
A file_has_bom() 0 8 2
A str_begins() 0 3 1
A max() 0 14 3
B str_camelize() 0 74 10
A parse_str() 0 18 4
A filter_input() 0 16 3
A str_contains() 0 10 2
B str_to_lines() 0 29 8
A substr_in_byte() 0 18 6
A stripos_in_byte() 0 12 4
A get_unique_string() 0 22 3
A is_bom() 0 10 3
A is_hexadecimal() 0 8 2
A strnatcasecmp() 0 5 1
A encode_mimeheader() 0 26 5
A substr_left() 0 15 4
A count_chars() 0 11 1
D strlen() 0 104 19
A str_isubstr_last() 0 25 4
A to_int() 0 7 2
A ctype_loaded() 0 3 1
A str_replace_beginning() 0 25 6
A has_uppercase() 0 8 2
A remove_left() 0 28 4
C stripos() 0 67 14
A str_offset_exists() 0 10 2
D strrchr() 0 104 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 27 5
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 72 15
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
D chr() 0 109 19
A html_escape() 0 6 1
A toUTF8() 0 3 1
B str_obfuscate() 0 47 8
A string() 0 16 4
D normalize_encoding() 0 147 16
B rxClass() 0 45 8
B get_file_type() 0 65 7
A str_ensure_right() 0 13 4
A chr_to_int() 0 3 1
B str_titleize_for_humans() 0 171 7
C is_utf16() 0 71 16
A isHtml() 0 3 1
C filter() 0 57 12
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
C substr_count_in_byte() 0 55 15
A decode_mimeheader() 0 8 3
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 27 5
C str_longest_common_substring() 0 76 16
A regex_replace() 0 20 3
A chunk_split() 0 3 1
A titlecase() 0 35 5
A getData() 0 6 1
A str_iindex_first() 0 11 1
B strtolower() 0 60 10
B urldecode() 0 51 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 str_split_array() 0 17 2
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 51 9
A first_char() 0 14 4
A css_identifier() 0 56 6
A to_boolean() 0 35 5
C stristr() 0 79 17
A isUtf8() 0 3 1
A strncasecmp() 0 10 1
B strwidth() 0 43 8
A str_iends() 0 3 1
A css_stripe_media_queries() 0 6 1
A trim() 0 27 5
A clean() 0 48 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
D substr_count() 0 73 17
A strnatcmp() 0 9 2
D str_pad() 0 146 16
A urldecode_unicode_helper() 0 8 2
A str_ireplace() 0 31 5
A to_latin1() 0 3 1
A str_replace_ending() 0 24 6
A string_has_bom() 0 10 3
B strtr() 0 42 11
B str_contains_all() 0 24 9
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 72 23
B strspn() 0 30 10
A strcasecmp() 0 21 1
A str_transliterate() 0 6 1
B rawurldecode() 0 51 8
A str_ends() 0 3 1
B str_capitalize_name_helper() 0 86 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 18 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 15 2
A decimal_to_chr() 0 3 1
A to_iso8859() 0 16 4
A has_whitespace() 0 8 2
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 86 18
A codepoints() 0 36 5
A substr_right() 0 31 6
A lowerCaseFirst() 0 13 1
D str_split() 0 138 29
A str_ends_with_any() 0 13 4
A chr_map() 0 5 1
A strrpos_in_byte() 0 12 4
A cleanup() 0 24 2
A remove_right() 0 25 4
F strrpos() 0 136 31
A remove_html_breaks() 0 3 1
A showSupport() 0 17 3
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 38 9
A intlChar_loaded() 0 3 1
B strtocasefold() 0 33 7
A lcfirst() 0 44 5
A tabs_to_spaces() 0 11 3
B is_url() 0 44 7
A finfo_loaded() 0 3 1
B str_truncate() 0 44 7
F strripos() 0 113 25
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 4
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 chr_size_list() 0 17 3
A remove_bom() 0 22 5
A str_repeat() 0 5 1
A strpbrk() 0 11 4
D to_utf8_string() 0 110 33
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 31 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 57 6
A int_to_chr() 0 3 1
A is_lowercase() 0 8 2
A str_sort() 0 15 3
A to_utf8() 0 14 3
A ucword() 0 6 1
A str_underscored() 0 3 1
A str_offset_get() 0 14 4
A strip_whitespace() 0 7 2
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 53 11
A iconv_loaded() 0 3 1
A lcwords() 0 34 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 15 2
A substr_ileft() 0 15 4
A is_empty() 0 3 1
B html_encode() 0 54 11
A str_dasherize() 0 3 1
A isUtf16() 0 3 1
A str_ensure_left() 0 11 3
F encode() 0 147 37
B urldecode_fix_win1252_chars() 0 227 1
A toIso8859() 0 3 1
C is_utf32() 0 71 16
C ord() 0 77 16
B to_string() 0 33 8
A is_alphanumeric() 0 8 2
A strtonatfold() 0 13 2
A json_decode() 0 14 2
A fix_simple_utf8() 0 32 4
C strcspn() 0 49 12
A checkForSupport() 0 48 4
A is_printable() 0 3 1
B is_json() 0 27 8
A fixStrCaseHelper() 0 41 5
A int_to_hex() 0 7 2
B str_split_pattern() 0 49 11
D strstr() 0 107 21
A has_lowercase() 0 8 2
A json_encode() 0 10 2
A str_isubstr_first() 0 25 4
A is_base64() 0 17 5
A str_last_char() 0 16 4
A str_ireplace_beginning() 0 22 6
A hex_to_int() 0 14 3
A htmlentities() 0 28 3
A hex_to_chr() 0 4 1
A str_substr_before_first_separator() 0 32 6
F substr() 0 138 31
A isJson() 0 3 1
A wordwrap_per_line() 0 28 5
A str_surround() 0 3 1
A strncmp() 0 19 4
A filter_input_array() 0 15 3
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 43 5
A chr_to_hex() 0 11 3
D is_utf8_string() 0 134 28
A to_utf8_convert_helper() 0 28 5
B str_delimit() 0 33 8
B strtoupper() 0 60 10
A min() 0 14 3
A is_punctuation() 0 3 1
A collapse_whitespace() 0 8 2
C html_entity_decode() 0 59 13
A str_starts_with_any() 0 17 5
B strrichr() 0 54 11
A split() 0 7 1
A str_istarts_with_any() 0 17 5
B str_contains_any() 0 29 8
A initEmojiData() 0 29 4
A remove_duplicates() 0 16 4
B str_slice() 0 33 10
F strpos() 0 151 33
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
A emoji_from_country_code() 0 17 3

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
/**
8
 * @psalm-immutable
9
 */
10
final class UTF8
11
{
12
    /**
13
     * (CRLF|([ZWNJ-ZWJ]|T+|L*(LV?V+|LV|LVT)T*|L+|[^Control])[Extend]*|[Control])
14
     * This regular expression is a work around for http://bugs.exim.org/1279
15
     *
16
     * @deprecated <p>please don't use it anymore</p>
17
     */
18
    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}])";
19
20
    /**
21
     * Bom => Byte-Length
22
     *
23
     * INFO: https://en.wikipedia.org/wiki/Byte_order_mark
24
     *
25
     * @var array<string, int>
26
     */
27
    private static $BOM = [
28
        "\xef\xbb\xbf"     => 3, // UTF-8 BOM
29
        ''              => 6, // UTF-8 BOM as "WINDOWS-1252" (one char has [maybe] more then one byte ...)
30
        "\x00\x00\xfe\xff" => 4, // UTF-32 (BE) BOM
31
        '  þÿ'             => 6, // UTF-32 (BE) BOM as "WINDOWS-1252"
32
        "\xff\xfe\x00\x00" => 4, // UTF-32 (LE) BOM
33
        'ÿþ  '             => 6, // UTF-32 (LE) BOM as "WINDOWS-1252"
34
        "\xfe\xff"         => 2, // UTF-16 (BE) BOM
35
        'þÿ'               => 4, // UTF-16 (BE) BOM as "WINDOWS-1252"
36
        "\xff\xfe"         => 2, // UTF-16 (LE) BOM
37
        'ÿþ'               => 4, // UTF-16 (LE) BOM as "WINDOWS-1252"
38
    ];
39
40
    /**
41
     * Numeric code point => UTF-8 Character
42
     *
43
     * url: http://www.w3schools.com/charsets/ref_utf_punctuation.asp
44
     *
45
     * @var array<int, string>
46
     */
47
    private static $WHITESPACE = [
48
        // NULL Byte
49
        0 => "\x0",
50
        // Tab
51
        9 => "\x9",
52
        // New Line
53
        10 => "\xa",
54
        // Vertical Tab
55
        11 => "\xb",
56
        // Carriage Return
57
        13 => "\xd",
58
        // Ordinary Space
59
        32 => "\x20",
60
        // NO-BREAK SPACE
61
        160 => "\xc2\xa0",
62
        // OGHAM SPACE MARK
63
        5760 => "\xe1\x9a\x80",
64
        // MONGOLIAN VOWEL SEPARATOR
65
        6158 => "\xe1\xa0\x8e",
66
        // EN QUAD
67
        8192 => "\xe2\x80\x80",
68
        // EM QUAD
69
        8193 => "\xe2\x80\x81",
70
        // EN SPACE
71
        8194 => "\xe2\x80\x82",
72
        // EM SPACE
73
        8195 => "\xe2\x80\x83",
74
        // THREE-PER-EM SPACE
75
        8196 => "\xe2\x80\x84",
76
        // FOUR-PER-EM SPACE
77
        8197 => "\xe2\x80\x85",
78
        // SIX-PER-EM SPACE
79
        8198 => "\xe2\x80\x86",
80
        // FIGURE SPACE
81
        8199 => "\xe2\x80\x87",
82
        // PUNCTUATION SPACE
83
        8200 => "\xe2\x80\x88",
84
        // THIN SPACE
85
        8201 => "\xe2\x80\x89",
86
        // HAIR SPACE
87
        8202 => "\xe2\x80\x8a",
88
        // LINE SEPARATOR
89
        8232 => "\xe2\x80\xa8",
90
        // PARAGRAPH SEPARATOR
91
        8233 => "\xe2\x80\xa9",
92
        // NARROW NO-BREAK SPACE
93
        8239 => "\xe2\x80\xaf",
94
        // MEDIUM MATHEMATICAL SPACE
95
        8287 => "\xe2\x81\x9f",
96
        // HALFWIDTH HANGUL FILLER
97
        65440 => "\xef\xbe\xa0",
98
        // IDEOGRAPHIC SPACE
99
        12288 => "\xe3\x80\x80",
100
    ];
101
102
    /**
103
     * @var array<string, string>
104
     */
105
    private static $WHITESPACE_TABLE = [
106
        'SPACE'                     => "\x20",
107
        'NO-BREAK SPACE'            => "\xc2\xa0",
108
        'OGHAM SPACE MARK'          => "\xe1\x9a\x80",
109
        'EN QUAD'                   => "\xe2\x80\x80",
110
        'EM QUAD'                   => "\xe2\x80\x81",
111
        'EN SPACE'                  => "\xe2\x80\x82",
112
        'EM SPACE'                  => "\xe2\x80\x83",
113
        'THREE-PER-EM SPACE'        => "\xe2\x80\x84",
114
        'FOUR-PER-EM SPACE'         => "\xe2\x80\x85",
115
        'SIX-PER-EM SPACE'          => "\xe2\x80\x86",
116
        'FIGURE SPACE'              => "\xe2\x80\x87",
117
        'PUNCTUATION SPACE'         => "\xe2\x80\x88",
118
        'THIN SPACE'                => "\xe2\x80\x89",
119
        'HAIR SPACE'                => "\xe2\x80\x8a",
120
        'LINE SEPARATOR'            => "\xe2\x80\xa8",
121
        'PARAGRAPH SEPARATOR'       => "\xe2\x80\xa9",
122
        'ZERO WIDTH SPACE'          => "\xe2\x80\x8b",
123
        'NARROW NO-BREAK SPACE'     => "\xe2\x80\xaf",
124
        'MEDIUM MATHEMATICAL SPACE' => "\xe2\x81\x9f",
125
        'IDEOGRAPHIC SPACE'         => "\xe3\x80\x80",
126
        'HALFWIDTH HANGUL FILLER'   => "\xef\xbe\xa0",
127
    ];
128
129
    /**
130
     * @var array
131
     *
132
     * @phpstan-var array{upper: string[], lower: string[]}
133
     */
134
    private static $COMMON_CASE_FOLD = [
135
        'upper' => [
136
            'µ',
137
            'ſ',
138
            "\xCD\x85",
139
            'ς',
140
            'ẞ',
141
            "\xCF\x90",
142
            "\xCF\x91",
143
            "\xCF\x95",
144
            "\xCF\x96",
145
            "\xCF\xB0",
146
            "\xCF\xB1",
147
            "\xCF\xB5",
148
            "\xE1\xBA\x9B",
149
            "\xE1\xBE\xBE",
150
        ],
151
        'lower' => [
152
            'μ',
153
            's',
154
            'ι',
155
            'σ',
156
            'ß',
157
            'β',
158
            'θ',
159
            'φ',
160
            'π',
161
            'κ',
162
            'ρ',
163
            'ε',
164
            "\xE1\xB9\xA1",
165
            'ι',
166
        ],
167
    ];
168
169
    /**
170
     * @var array
171
     *
172
     * @phpstan-var array<string, mixed>
173
     */
174
    private static $SUPPORT = [];
175
176
    /**
177
     * @var string[]|null
178
     *
179
     * @phpstan-var array<string, string>|null
180
     */
181
    private static $BROKEN_UTF8_FIX;
182
183
    /**
184
     * @var string[]|null
185
     *
186
     * @phpstan-var array<int, string>|null
187
     */
188
    private static $WIN1252_TO_UTF8;
189
190
    /**
191
     * @var string[]|null
192
     *
193
     * @phpstan-var array<int ,string>|null
194
     */
195
    private static $INTL_TRANSLITERATOR_LIST;
196
197
    /**
198
     * @var string[]|null
199
     *
200
     * @phpstan-var array<string>|null
201
     */
202
    private static $ENCODINGS;
203
204
    /**
205
     * @var int[]|null
206
     *
207
     * @phpstan-var array<string ,int>|null
208
     */
209
    private static $ORD;
210
211
    /**
212
     * @var string[]|null
213
     *
214
     * @phpstan-var array<string, string>|null
215
     */
216
    private static $EMOJI;
217
218
    /**
219
     * @var string[]|null
220
     *
221
     * @phpstan-var array<string>|null
222
     */
223
    private static $EMOJI_VALUES_CACHE;
224
225
    /**
226
     * @var string[]|null
227
     *
228
     * @phpstan-var array<string>|null
229
     */
230
    private static $EMOJI_KEYS_CACHE;
231
232
    /**
233
     * @var string[]|null
234
     *
235
     * @phpstan-var array<string>|null
236
     */
237
    private static $EMOJI_KEYS_REVERSIBLE_CACHE;
238
239
    /**
240
     * @var string[]|null
241
     *
242
     * @phpstan-var array<int, string>|null
243
     */
244
    private static $CHR;
245
246
    /**
247
     * __construct()
248
     */
249 34
    public function __construct()
250
    {
251 34
    }
252
253
    /**
254
     * Return the character at the specified position: $str[1] like functionality.
255
     *
256
     * EXAMPLE: <code>UTF8::access('fòô', 1); // 'ò'</code>
257
     *
258
     * @param string $str      <p>A UTF-8 string.</p>
259
     * @param int    $pos      <p>The position of character to return.</p>
260
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
261
     *
262
     * @psalm-pure
263
     *
264
     * @return string
265
     *                <p>Single multi-byte character.</p>
266
     */
267 3
    public static function access(string $str, int $pos, string $encoding = 'UTF-8'): string
268
    {
269 3
        if ($str === '' || $pos < 0) {
270 2
            return '';
271
        }
272
273 3
        if ($encoding === 'UTF-8') {
274 3
            return (string) \mb_substr($str, $pos, 1);
275
        }
276
277
        return (string) self::substr($str, $pos, 1, $encoding);
278
    }
279
280
    /**
281
     * Prepends UTF-8 BOM character to the string and returns the whole string.
282
     *
283
     * INFO: If BOM already existed there, the Input string is returned.
284
     *
285
     * EXAMPLE: <code>UTF8::add_bom_to_string('fòô'); // "\xEF\xBB\xBF" . 'fòô'</code>
286
     *
287
     * @param string $str <p>The input string.</p>
288
     *
289
     * @psalm-pure
290
     *
291
     * @return string
292
     *                <p>The output string that contains BOM.</p>
293
     */
294 2
    public static function add_bom_to_string(string $str): string
295
    {
296 2
        if (!self::string_has_bom($str)) {
297 2
            $str = self::bom() . $str;
298
        }
299
300 2
        return $str;
301
    }
302
303
    /**
304
     * Changes all keys in an array.
305
     *
306
     * @param array<string, mixed> $array    <p>The array to work on</p>
307
     * @param int                  $case     [optional] <p> Either <strong>CASE_UPPER</strong><br>
308
     *                                       or <strong>CASE_LOWER</strong> (default)</p>
309
     * @param string               $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
310
     *
311
     * @psalm-pure
312
     *
313
     * @return string[]
314
     *                  <p>An array with its keys lower- or uppercased.</p>
315
     */
316 2
    public static function array_change_key_case(
317
        array $array,
318
        int $case = \CASE_LOWER,
319
        string $encoding = 'UTF-8'
320
    ): array {
321
        if (
322 2
            $case !== \CASE_LOWER
323
            &&
324 2
            $case !== \CASE_UPPER
325
        ) {
326
            $case = \CASE_LOWER;
327
        }
328
329 2
        $return = [];
330 2
        foreach ($array as $key => &$value) {
331 2
            $key = $case === \CASE_LOWER
332 2
                ? self::strtolower((string) $key, $encoding)
333 2
                : self::strtoupper((string) $key, $encoding);
334
335 2
            $return[$key] = $value;
336
        }
337
338 2
        return $return;
339
    }
340
341
    /**
342
     * Returns the substring between $start and $end, if found, or an empty
343
     * string. An optional offset may be supplied from which to begin the
344
     * search for the start string.
345
     *
346
     * @param string $str
347
     * @param string $start    <p>Delimiter marking the start of the substring.</p>
348
     * @param string $end      <p>Delimiter marking the end of the substring.</p>
349
     * @param int    $offset   [optional] <p>Index from which to begin the search. Default: 0</p>
350
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
351
     *
352
     * @psalm-pure
353
     *
354
     * @return string
355
     */
356 16
    public static function between(
357
        string $str,
358
        string $start,
359
        string $end,
360
        int $offset = 0,
361
        string $encoding = 'UTF-8'
362
    ): string {
363 16
        if ($encoding === 'UTF-8') {
364 8
            $start_position = \mb_strpos($str, $start, $offset);
365 8
            if ($start_position === false) {
366 1
                return '';
367
            }
368
369 7
            $substr_index = $start_position + (int) \mb_strlen($start);
370 7
            $end_position = \mb_strpos($str, $end, $substr_index);
371
            if (
372 7
                $end_position === false
373
                ||
374 7
                $end_position === $substr_index
375
            ) {
376 2
                return '';
377
            }
378
379 5
            return (string) \mb_substr($str, $substr_index, $end_position - $substr_index);
380
        }
381
382 8
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
383
384 8
        $start_position = self::strpos($str, $start, $offset, $encoding);
385 8
        if ($start_position === false) {
386 1
            return '';
387
        }
388
389 7
        $substr_index = $start_position + (int) self::strlen($start, $encoding);
390 7
        $end_position = self::strpos($str, $end, $substr_index, $encoding);
391
        if (
392 7
            $end_position === false
393
            ||
394 7
            $end_position === $substr_index
395
        ) {
396 2
            return '';
397
        }
398
399 5
        return (string) self::substr(
400 5
            $str,
401 5
            $substr_index,
402 5
            $end_position - $substr_index,
403 5
            $encoding
404
        );
405
    }
406
407
    /**
408
     * Convert binary into a string.
409
     *
410
     * INFO: opposite to UTF8::str_to_binary()
411
     *
412
     * EXAMPLE: <code>UTF8::binary_to_str('11110000100111111001100010000011'); // '😃'</code>
413
     *
414
     * @param string $bin 1|0
415
     *
416
     * @psalm-pure
417
     *
418
     * @return string
419
     */
420 2
    public static function binary_to_str($bin): string
421
    {
422 2
        if (!isset($bin[0])) {
423
            return '';
424
        }
425
426 2
        $convert = \base_convert($bin, 2, 16);
427 2
        if ($convert === '0') {
428 1
            return '';
429
        }
430
431 2
        return \pack('H*', $convert);
432
    }
433
434
    /**
435
     * Returns the UTF-8 Byte Order Mark Character.
436
     *
437
     * INFO: take a look at UTF8::$bom for e.g. UTF-16 and UTF-32 BOM values
438
     *
439
     * EXAMPLE: <code>UTF8::bom(); // "\xEF\xBB\xBF"</code>
440
     *
441
     * @psalm-pure
442
     *
443
     * @return string
444
     *                <p>UTF-8 Byte Order Mark.</p>
445
     */
446 4
    public static function bom(): string
447
    {
448 4
        return "\xef\xbb\xbf";
449
    }
450
451
    /**
452
     * @alias of UTF8::chr_map()
453
     *
454
     * @param callable $callback
455
     * @param string   $str
456
     *
457
     * @psalm-pure
458
     *
459
     * @return string[]
460
     *
461
     * @see   UTF8::chr_map()
462
     */
463 2
    public static function callback($callback, string $str): array
464
    {
465 2
        return self::chr_map($callback, $str);
466
    }
467
468
    /**
469
     * Returns the character at $index, with indexes starting at 0.
470
     *
471
     * @param string $str      <p>The input string.</p>
472
     * @param int    $index    <p>Position of the character.</p>
473
     * @param string $encoding [optional] <p>Default is UTF-8</p>
474
     *
475
     * @psalm-pure
476
     *
477
     * @return string
478
     *                <p>The character at $index.</p>
479
     */
480 9
    public static function char_at(string $str, int $index, string $encoding = 'UTF-8'): string
481
    {
482 9
        if ($encoding === 'UTF-8') {
483 5
            return (string) \mb_substr($str, $index, 1);
484
        }
485
486 4
        return (string) self::substr($str, $index, 1, $encoding);
487
    }
488
489
    /**
490
     * Returns an array consisting of the characters in the string.
491
     *
492
     * @param string $str <p>The input string.</p>
493
     *
494
     * @psalm-pure
495
     *
496
     * @return string[]
497
     *                  <p>An array of chars.</p>
498
     */
499 4
    public static function chars(string $str): array
500
    {
501
        /** @var string[] */
502 4
        return self::str_split($str);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::str_split($str) returns an array which contains values of type array|string[] which are incompatible with the documented value type string.
Loading history...
503
    }
504
505
    /**
506
     * This method will auto-detect your server environment for UTF-8 support.
507
     *
508
     * @return true|null
509
     *
510
     * @internal <p>You don't need to run it manually, it will be triggered if it's needed.</p>
511
     */
512 5
    public static function checkForSupport()
513
    {
514 5
        if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
515
            self::$SUPPORT['already_checked_via_portable_utf8'] = true;
516
517
            // http://php.net/manual/en/book.mbstring.php
518
            self::$SUPPORT['mbstring'] = self::mbstring_loaded();
519
520
            self::$SUPPORT['mbstring_func_overload'] = self::mbstring_overloaded();
521
            if (self::$SUPPORT['mbstring'] === true) {
522
                \mb_internal_encoding('UTF-8');
523
                /** @noinspection UnusedFunctionResultInspection */
524
                /** @noinspection PhpComposerExtensionStubsInspection */
525
                \mb_regex_encoding('UTF-8');
526
                self::$SUPPORT['mbstring_internal_encoding'] = 'UTF-8';
527
            }
528
529
            // http://php.net/manual/en/book.iconv.php
530
            self::$SUPPORT['iconv'] = self::iconv_loaded();
531
532
            // http://php.net/manual/en/book.intl.php
533
            self::$SUPPORT['intl'] = self::intl_loaded();
534
535
            // http://php.net/manual/en/class.intlchar.php
536
            self::$SUPPORT['intlChar'] = self::intlChar_loaded();
537
538
            // http://php.net/manual/en/book.ctype.php
539
            self::$SUPPORT['ctype'] = self::ctype_loaded();
540
541
            // http://php.net/manual/en/class.finfo.php
542
            self::$SUPPORT['finfo'] = self::finfo_loaded();
543
544
            // http://php.net/manual/en/book.json.php
545
            self::$SUPPORT['json'] = self::json_loaded();
546
547
            // http://php.net/manual/en/book.pcre.php
548
            self::$SUPPORT['pcre_utf8'] = self::pcre_utf8_support();
549
550
            self::$SUPPORT['symfony_polyfill_used'] = self::symfony_polyfill_used();
551
            if (self::$SUPPORT['symfony_polyfill_used'] === true) {
552
                \mb_internal_encoding('UTF-8');
553
                self::$SUPPORT['mbstring_internal_encoding'] = 'UTF-8';
554
            }
555
556
            return true;
557
        }
558
559 5
        return null;
560
    }
561
562
    /**
563
     * Generates a UTF-8 encoded character from the given code point.
564
     *
565
     * INFO: opposite to UTF8::ord()
566
     *
567
     * EXAMPLE: <code>UTF8::chr(0x2603); // '☃'</code>
568
     *
569
     * @param int    $code_point <p>The code point for which to generate a character.</p>
570
     * @param string $encoding   [optional] <p>Default is UTF-8</p>
571
     *
572
     * @psalm-pure
573
     *
574
     * @return string|null
575
     *                     <p>Multi-byte character, returns null on failure or empty input.</p>
576
     */
577 21
    public static function chr($code_point, string $encoding = 'UTF-8')
578
    {
579
        // init
580
        /**
581
         * @psalm-suppress ImpureStaticVariable
582
         *
583
         * @var array<string,string>
584
         */
585 21
        static $CHAR_CACHE = [];
586
587 21
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
588 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
589
        }
590
591
        /** @noinspection InArrayCanBeUsedInspection */
592
        if (
593 21
            $encoding !== 'UTF-8'
594
            &&
595 21
            $encoding !== 'ISO-8859-1'
596
            &&
597 21
            $encoding !== 'WINDOWS-1252'
598
            &&
599 21
            self::$SUPPORT['mbstring'] === false
600
        ) {
601
            /**
602
             * @psalm-suppress ImpureFunctionCall - is is only a warning
603
             */
604
            \trigger_error('UTF8::chr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
605
        }
606
607 21
        if (!\is_int($code_point) || $code_point <= 0) {
0 ignored issues
show
introduced by
The condition is_int($code_point) is always true.
Loading history...
608 5
            return null;
609
        }
610
611 21
        $cache_key = $code_point . '_' . $encoding;
612 21
        if (isset($CHAR_CACHE[$cache_key])) {
613 19
            return $CHAR_CACHE[$cache_key];
614
        }
615
616 10
        if ($code_point <= 0x80) { // only for "simple"-chars
617
618 9
            if (self::$CHR === null) {
619
                self::$CHR = self::getData('chr');
620
            }
621
622
            /**
623
             * @psalm-suppress PossiblyNullArrayAccess
624
             */
625 9
            $chr = self::$CHR[$code_point];
626
627 9
            if ($encoding !== 'UTF-8') {
628 1
                $chr = self::encode($encoding, $chr);
629
            }
630
631 9
            return $CHAR_CACHE[$cache_key] = $chr;
632
        }
633
634
        //
635
        // fallback via "IntlChar"
636
        //
637
638 6
        if (self::$SUPPORT['intlChar'] === true) {
639
            /** @noinspection PhpComposerExtensionStubsInspection */
640 6
            $chr = \IntlChar::chr($code_point);
641
642 6
            if ($encoding !== 'UTF-8') {
643
                $chr = self::encode($encoding, $chr);
644
            }
645
646 6
            return $CHAR_CACHE[$cache_key] = $chr;
647
        }
648
649
        //
650
        // fallback via vanilla php
651
        //
652
653
        if (self::$CHR === null) {
654
            self::$CHR = self::getData('chr');
655
        }
656
657
        $code_point = (int) $code_point;
658
        if ($code_point <= 0x7FF) {
659
            /**
660
             * @psalm-suppress PossiblyNullArrayAccess
661
             */
662
            $chr = self::$CHR[($code_point >> 6) + 0xC0] .
663
                   self::$CHR[($code_point & 0x3F) + 0x80];
664
        } elseif ($code_point <= 0xFFFF) {
665
            /**
666
             * @psalm-suppress PossiblyNullArrayAccess
667
             */
668
            $chr = self::$CHR[($code_point >> 12) + 0xE0] .
669
                   self::$CHR[(($code_point >> 6) & 0x3F) + 0x80] .
670
                   self::$CHR[($code_point & 0x3F) + 0x80];
671
        } else {
672
            /**
673
             * @psalm-suppress PossiblyNullArrayAccess
674
             */
675
            $chr = self::$CHR[($code_point >> 18) + 0xF0] .
676
                   self::$CHR[(($code_point >> 12) & 0x3F) + 0x80] .
677
                   self::$CHR[(($code_point >> 6) & 0x3F) + 0x80] .
678
                   self::$CHR[($code_point & 0x3F) + 0x80];
679
        }
680
681
        if ($encoding !== 'UTF-8') {
682
            $chr = self::encode($encoding, $chr);
683
        }
684
685
        return $CHAR_CACHE[$cache_key] = $chr;
686
    }
687
688
    /**
689
     * Applies callback to all characters of a string.
690
     *
691
     * EXAMPLE: <code>UTF8::chr_map([UTF8::class, 'strtolower'], 'Κόσμε'); // ['κ','ό', 'σ', 'μ', 'ε']</code>
692
     *
693
     * @param callable $callback <p>The callback function.</p>
694
     * @param string   $str      <p>UTF-8 string to run callback on.</p>
695
     *
696
     * @psalm-pure
697
     *
698
     * @return string[]
699
     *                  <p>The outcome of the callback, as array.</p>
700
     */
701 2
    public static function chr_map($callback, string $str): array
702
    {
703 2
        return \array_map(
704 2
            $callback,
705 2
            self::str_split($str)
706
        );
707
    }
708
709
    /**
710
     * Generates an array of byte length of each character of a Unicode string.
711
     *
712
     * 1 byte => U+0000  - U+007F
713
     * 2 byte => U+0080  - U+07FF
714
     * 3 byte => U+0800  - U+FFFF
715
     * 4 byte => U+10000 - U+10FFFF
716
     *
717
     * EXAMPLE: <code>UTF8::chr_size_list('中文空白-test'); // [3, 3, 3, 3, 1, 1, 1, 1, 1]</code>
718
     *
719
     * @param string $str <p>The original unicode string.</p>
720
     *
721
     * @psalm-pure
722
     *
723
     * @return int[]
724
     *               <p>An array of byte lengths of each character.</p>
725
     */
726 4
    public static function chr_size_list(string $str): array
727
    {
728 4
        if ($str === '') {
729 4
            return [];
730
        }
731
732 4
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
733
            return \array_map(
734
                static function (string $data): int {
735
                    // "mb_" is available if overload is used, so use it ...
736
                    return \mb_strlen($data, 'CP850'); // 8-BIT
737
                },
738
                self::str_split($str)
739
            );
740
        }
741
742 4
        return \array_map('\strlen', self::str_split($str));
743
    }
744
745
    /**
746
     * Get a decimal code representation of a specific character.
747
     *
748
     * INFO: opposite to UTF8::decimal_to_chr()
749
     *
750
     * EXAMPLE: <code>UTF8::chr_to_decimal('§'); // 0xa7</code>
751
     *
752
     * @param string $char <p>The input character.</p>
753
     *
754
     * @psalm-pure
755
     *
756
     * @return int
757
     */
758 5
    public static function chr_to_decimal(string $char): int
759
    {
760 5
        if (self::$SUPPORT['iconv'] === true) {
761 5
            $chr_tmp = \iconv('UTF-8', 'UCS-4LE', $char);
762 5
            if ($chr_tmp !== false) {
763
                /** @noinspection OffsetOperationsInspection */
764 5
                return \unpack('V', $chr_tmp)[1];
765
            }
766
        }
767
768
        $code = self::ord($char[0]);
769
        $bytes = 1;
770
771
        if (!($code & 0x80)) {
772
            // 0xxxxxxx
773
            return $code;
774
        }
775
776
        if (($code & 0xe0) === 0xc0) {
777
            // 110xxxxx
778
            $bytes = 2;
779
            $code &= ~0xc0;
780
        } elseif (($code & 0xf0) === 0xe0) {
781
            // 1110xxxx
782
            $bytes = 3;
783
            $code &= ~0xe0;
784
        } elseif (($code & 0xf8) === 0xf0) {
785
            // 11110xxx
786
            $bytes = 4;
787
            $code &= ~0xf0;
788
        }
789
790
        for ($i = 2; $i <= $bytes; ++$i) {
791
            // 10xxxxxx
792
            $code = ($code << 6) + (self::ord($char[$i - 1]) & ~0x80);
793
        }
794
795
        return $code;
796
    }
797
798
    /**
799
     * Get hexadecimal code point (U+xxxx) of a UTF-8 encoded character.
800
     *
801
     * EXAMPLE: <code>UTF8::chr_to_hex('§'); // U+00a7</code>
802
     *
803
     * @param int|string $char   <p>The input character</p>
804
     * @param string     $prefix [optional]
805
     *
806
     * @psalm-pure
807
     *
808
     * @return string
809
     *                <p>The code point encoded as U+xxxx.</p>
810
     */
811 2
    public static function chr_to_hex($char, string $prefix = 'U+'): string
812
    {
813 2
        if ($char === '') {
814 2
            return '';
815
        }
816
817 2
        if ($char === '&#0;') {
818 2
            $char = '';
819
        }
820
821 2
        return self::int_to_hex(self::ord((string) $char), $prefix);
822
    }
823
824
    /**
825
     * alias for "UTF8::chr_to_decimal()"
826
     *
827
     * @param string $chr
828
     *
829
     * @psalm-pure
830
     *
831
     * @return int
832
     *
833
     * @see        UTF8::chr_to_decimal()
834
     * @deprecated <p>please use "UTF8::chr_to_decimal()"</p>
835
     */
836 2
    public static function chr_to_int(string $chr): int
837
    {
838 2
        return self::chr_to_decimal($chr);
839
    }
840
841
    /**
842
     * Splits a string into smaller chunks and multiple lines, using the specified line ending character.
843
     *
844
     * EXAMPLE: <code>UTF8::chunk_split('ABC-ÖÄÜ-中文空白-κόσμε', 3); // "ABC\r\n-ÖÄ\r\nÜ-中\r\n文空白\r\n-κό\r\nσμε"</code>
845
     *
846
     * @param string $body         <p>The original string to be split.</p>
847
     * @param int    $chunk_length [optional] <p>The maximum character length of a chunk.</p>
848
     * @param string $end          [optional] <p>The character(s) to be inserted at the end of each chunk.</p>
849
     *
850
     * @psalm-pure
851
     *
852
     * @return string
853
     *                <p>The chunked string.</p>
854
     */
855 4
    public static function chunk_split(string $body, int $chunk_length = 76, string $end = "\r\n"): string
856
    {
857 4
        return \implode($end, self::str_split($body, $chunk_length));
858
    }
859
860
    /**
861
     * Accepts a string and removes all non-UTF-8 characters from it + extras if needed.
862
     *
863
     * EXAMPLE: <code>UTF8::clean("\xEF\xBB\xBF„Abcdef\xc2\xa0\x20…” — 😃 - Düsseldorf", true, true); // '„Abcdef  …” — 😃 - Düsseldorf'</code>
864
     *
865
     * @param string $str                                     <p>The string to be sanitized.</p>
866
     * @param bool   $remove_bom                              [optional] <p>Set to true, if you need to remove
867
     *                                                        UTF-BOM.</p>
868
     * @param bool   $normalize_whitespace                    [optional] <p>Set to true, if you need to normalize the
869
     *                                                        whitespace.</p>
870
     * @param bool   $normalize_msword                        [optional] <p>Set to true, if you need to normalize MS
871
     *                                                        Word chars e.g.: "…"
872
     *                                                        => "..."</p>
873
     * @param bool   $keep_non_breaking_space                 [optional] <p>Set to true, to keep non-breaking-spaces,
874
     *                                                        in
875
     *                                                        combination with
876
     *                                                        $normalize_whitespace</p>
877
     * @param bool   $replace_diamond_question_mark           [optional] <p>Set to true, if you need to remove diamond
878
     *                                                        question mark e.g.: "�"</p>
879
     * @param bool   $remove_invisible_characters             [optional] <p>Set to false, if you not want to remove
880
     *                                                        invisible characters e.g.: "\0"</p>
881
     * @param bool   $remove_invisible_characters_url_encoded [optional] <p>Set to true, if you not want to remove
882
     *                                                        invisible url encoded characters e.g.: "%0B"<br> WARNING:
883
     *                                                        maybe contains false-positives e.g. aa%0Baa -> aaaa.
884
     *                                                        </p>
885
     *
886
     * @psalm-pure
887
     *
888
     * @return string
889
     *                <p>An clean UTF-8 encoded string.</p>
890
     *
891
     * @noinspection PhpTooManyParametersInspection
892
     */
893 90
    public static function clean(
894
        string $str,
895
        bool $remove_bom = false,
896
        bool $normalize_whitespace = false,
897
        bool $normalize_msword = false,
898
        bool $keep_non_breaking_space = false,
899
        bool $replace_diamond_question_mark = false,
900
        bool $remove_invisible_characters = true,
901
        bool $remove_invisible_characters_url_encoded = false
902
    ): string {
903
        // http://stackoverflow.com/questions/1401317/remove-non-utf8-characters-from-string
904
        // caused connection reset problem on larger strings
905
906 90
        $regex = '/
907
          (
908
            (?: [\x00-\x7F]               # single-byte sequences   0xxxxxxx
909
            |   [\xC0-\xDF][\x80-\xBF]    # double-byte sequences   110xxxxx 10xxxxxx
910
            |   [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences   1110xxxx 10xxxxxx * 2
911
            |   [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
912
            ){1,100}                      # ...one or more times
913
          )
914
        | ( [\x80-\xBF] )                 # invalid byte in range 10000000 - 10111111
915
        | ( [\xC0-\xFF] )                 # invalid byte in range 11000000 - 11111111
916
        /x';
917
        /** @noinspection NotOptimalRegularExpressionsInspection */
918 90
        $str = (string) \preg_replace($regex, '$1', $str);
919
920 90
        if ($replace_diamond_question_mark) {
921 33
            $str = self::replace_diamond_question_mark($str);
922
        }
923
924 90
        if ($remove_invisible_characters) {
925 90
            $str = self::remove_invisible_characters($str, $remove_invisible_characters_url_encoded);
926
        }
927
928 90
        if ($normalize_whitespace) {
929 37
            $str = self::normalize_whitespace($str, $keep_non_breaking_space);
930
        }
931
932 90
        if ($normalize_msword) {
933 4
            $str = self::normalize_msword($str);
934
        }
935
936 90
        if ($remove_bom) {
937 37
            $str = self::remove_bom($str);
938
        }
939
940 90
        return $str;
941
    }
942
943
    /**
944
     * Clean-up a string and show only printable UTF-8 chars at the end  + fix UTF-8 encoding.
945
     *
946
     * EXAMPLE: <code>UTF8::cleanup("\xEF\xBB\xBF„Abcdef\xc2\xa0\x20…” — 😃 - Düsseldorf", true, true); // '„Abcdef  …” — 😃 - Düsseldorf'</code>
947
     *
948
     * @param string $str <p>The input string.</p>
949
     *
950
     * @psalm-pure
951
     *
952
     * @return string
953
     */
954 33
    public static function cleanup($str): string
955
    {
956
        // init
957 33
        $str = (string) $str;
958
959 33
        if ($str === '') {
960 5
            return '';
961
        }
962
963
        // fixed ISO <-> UTF-8 Errors
964 33
        $str = self::fix_simple_utf8($str);
965
966
        // remove all none UTF-8 symbols
967
        // && remove diamond question mark (�)
968
        // && remove remove invisible characters (e.g. "\0")
969
        // && remove BOM
970
        // && normalize whitespace chars (but keep non-breaking-spaces)
971 33
        return self::clean(
972 33
            $str,
973 33
            true,
974 33
            true,
975 33
            false,
976 33
            true,
977 33
            true
978
        );
979
    }
980
981
    /**
982
     * Accepts a string or a array of strings and returns an array of Unicode code points.
983
     *
984
     * INFO: opposite to UTF8::string()
985
     *
986
     * EXAMPLE: <code>
987
     * UTF8::codepoints('κöñ'); // array(954, 246, 241)
988
     * // ... OR ...
989
     * UTF8::codepoints('κöñ', true); // array('U+03ba', 'U+00f6', 'U+00f1')
990
     * </code>
991
     *
992
     * @param string|string[] $arg         <p>A UTF-8 encoded string or an array of such strings.</p>
993
     * @param bool            $use_u_style <p>If True, will return code points in U+xxxx format,
994
     *                                     default, code points will be returned as integers.</p>
995
     *
996
     * @psalm-pure
997
     *
998
     * @return int[]|string[]
999
     *                        <p>
1000
     *                        The array of code points:<br>
1001
     *                        int[] for $u_style === false<br>
1002
     *                        string[] for $u_style === true<br>
1003
     *                        </p>
1004
     */
1005 12
    public static function codepoints($arg, bool $use_u_style = false): array
1006
    {
1007 12
        if (\is_string($arg)) {
1008 12
            $arg = self::str_split($arg);
1009
        }
1010
1011
        /**
1012
         * @psalm-suppress DocblockTypeContradiction
1013
         */
1014 12
        if (!\is_array($arg)) {
0 ignored issues
show
introduced by
The condition is_array($arg) is always true.
Loading history...
1015 4
            return [];
1016
        }
1017
1018 12
        if ($arg === []) {
1019 7
            return [];
1020
        }
1021
1022 11
        $arg = \array_map(
1023
            [
1024 11
                self::class,
1025
                'ord',
1026
            ],
1027 11
            $arg
1028
        );
1029
1030 11
        if ($use_u_style) {
1031 2
            $arg = \array_map(
1032
                [
1033 2
                    self::class,
1034
                    'int_to_hex',
1035
                ],
1036 2
                $arg
1037
            );
1038
        }
1039
1040 11
        return $arg;
1041
    }
1042
1043
    /**
1044
     * Trims the string and replaces consecutive whitespace characters with a
1045
     * single space. This includes tabs and newline characters, as well as
1046
     * multibyte whitespace such as the thin space and ideographic space.
1047
     *
1048
     * @param string $str <p>The input string.</p>
1049
     *
1050
     * @psalm-pure
1051
     *
1052
     * @return string
1053
     *                <p>A string with trimmed $str and condensed whitespace.</p>
1054
     */
1055 13
    public static function collapse_whitespace(string $str): string
1056
    {
1057 13
        if (self::$SUPPORT['mbstring'] === true) {
1058
            /** @noinspection PhpComposerExtensionStubsInspection */
1059 13
            return \trim((string) \mb_ereg_replace('[[:space:]]+', ' ', $str));
1060
        }
1061
1062
        return \trim(self::regex_replace($str, '[[:space:]]+', ' '));
1063
    }
1064
1065
    /**
1066
     * Returns count of characters used in a string.
1067
     *
1068
     * EXAMPLE: <code>UTF8::count_chars('κaκbκc'); // array('κ' => 3, 'a' => 1, 'b' => 1, 'c' => 1)</code>
1069
     *
1070
     * @param string $str                     <p>The input string.</p>
1071
     * @param bool   $clean_utf8              [optional] <p>Remove non UTF-8 chars from the string.</p>
1072
     * @param bool   $try_to_use_mb_functions [optional] <p>Set to false, if you don't want to use
1073
     *
1074
     * @psalm-pure
1075
     *
1076
     * @return int[]
1077
     *               <p>An associative array of Character as keys and
1078
     *               their count as values.</p>
1079
     */
1080 19
    public static function count_chars(
1081
        string $str,
1082
        bool $clean_utf8 = false,
1083
        bool $try_to_use_mb_functions = true
1084
    ): array {
1085 19
        return \array_count_values(
1086 19
            self::str_split(
1087 19
                $str,
1088 19
                1,
1089 19
                $clean_utf8,
1090 19
                $try_to_use_mb_functions
1091
            )
1092
        );
1093
    }
1094
1095
    /**
1096
     * Create a valid CSS identifier for e.g. "class"- or "id"-attributes.
1097
     *
1098
     * EXAMPLE: <code>UTF8::css_identifier('123foo/bar!!!'); // _23foo-bar</code>
1099
     *
1100
     * copy&past from https://github.com/drupal/core/blob/8.8.x/lib/Drupal/Component/Utility/Html.php#L95
1101
     *
1102
     * @param string   $str        <p>INFO: if no identifier is given e.g. " " or "", we will create a unique string automatically</p>
1103
     * @param string[] $filter
1104
     * @param bool     $strip_tags
1105
     * @param bool     $strtolower
1106
     *
1107
     * @psalm-pure
1108
     *
1109
     * @return string
1110
     *
1111
     * @phpstan-param array<string,string> $filter
1112
     */
1113 1
    public static function css_identifier(
1114
        string $str = '',
1115
        array $filter = [
1116
            ' ' => '-',
1117
            '/' => '-',
1118
            '[' => '',
1119
            ']' => '',
1120
        ],
1121
        bool $strip_tags = false,
1122
        bool $strtolower = true
1123
    ): string {
1124
        // We could also use strtr() here but its much slower than str_replace(). In
1125
        // order to keep '__' to stay '__' we first replace it with a different
1126
        // placeholder after checking that it is not defined as a filter.
1127 1
        $double_underscore_replacements = 0;
1128
1129
        // Fallback ...
1130 1
        if (\trim($str) === '') {
1131 1
            $str = \uniqid('auto-generated-css-class', true);
1132
        } else {
1133 1
            $str = self::clean($str);
1134
        }
1135
1136 1
        if ($strip_tags) {
1137
            $str = \strip_tags($str);
1138
        }
1139
1140 1
        if ($strtolower) {
1141 1
            $str = \strtolower($str);
1142
        }
1143
1144 1
        if (!isset($filter['__'])) {
1145 1
            $str = \str_replace('__', '##', $str, $double_underscore_replacements);
1146
        }
1147
1148
        /* @noinspection ArrayValuesMissUseInspection */
1149 1
        $str = \str_replace(\array_keys($filter), \array_values($filter), $str);
1150
        // Replace temporary placeholder '##' with '__' only if the original
1151
        // $identifier contained '__'.
1152 1
        if ($double_underscore_replacements > 0) {
1153
            $str = \str_replace('##', '__', $str);
1154
        }
1155
1156
        // Valid characters in a CSS identifier are:
1157
        // - the hyphen (U+002D)
1158
        // - a-z (U+0030 - U+0039)
1159
        // - A-Z (U+0041 - U+005A)
1160
        // - the underscore (U+005F)
1161
        // - 0-9 (U+0061 - U+007A)
1162
        // - ISO 10646 characters U+00A1 and higher
1163
        // We strip out any character not in the above list.
1164 1
        $str = (string) \preg_replace('/[^\x{002D}\x{0030}-\x{0039}\x{0041}-\x{005A}\x{005F}\x{0061}-\x{007A}\x{00A1}-\x{FFFF}]/u', '', $str);
1165
        // Identifiers cannot start with a digit, two hyphens, or a hyphen followed by a digit.
1166 1
        $str = (string) \preg_replace(['/^[0-9]/', '/^(-[0-9])|^(--)/'], ['_', '__'], $str);
1167
1168 1
        return \trim($str, '-');
1169
    }
1170
1171
    /**
1172
     * Remove css media-queries.
1173
     *
1174
     * @param string $str
1175
     *
1176
     * @psalm-pure
1177
     *
1178
     * @return string
1179
     */
1180 1
    public static function css_stripe_media_queries(string $str): string
1181
    {
1182 1
        return (string) \preg_replace(
1183 1
            '#@media\\s+(?:only\\s)?(?:[\\s{(]|screen|all)\\s?[^{]+{.*}\\s*}\\s*#isumU',
1184 1
            '',
1185 1
            $str
1186
        );
1187
    }
1188
1189
    /**
1190
     * Checks whether ctype is available on the server.
1191
     *
1192
     * @psalm-pure
1193
     *
1194
     * @return bool
1195
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
1196
     *
1197
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
1198
     */
1199
    public static function ctype_loaded(): bool
1200
    {
1201
        return \extension_loaded('ctype');
1202
    }
1203
1204
    /**
1205
     * Converts an int value into a UTF-8 character.
1206
     *
1207
     * INFO: opposite to UTF8::string()
1208
     *
1209
     * EXAMPLE: <code>UTF8::decimal_to_chr(931); // 'Σ'</code>
1210
     *
1211
     * @param int|string $int
1212
     *
1213
     * @phpstan-param int|numeric-string $int
1214
     *
1215
     * @psalm-pure
1216
     *
1217
     * @return string
1218
     */
1219 20
    public static function decimal_to_chr($int): string
1220
    {
1221 20
        return self::html_entity_decode('&#' . $int . ';', \ENT_QUOTES | \ENT_HTML5);
1222
    }
1223
1224
    /**
1225
     * Decodes a MIME header field
1226
     *
1227
     * @param string $str
1228
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
1229
     *
1230
     * @psalm-pure
1231
     *
1232
     * @return false|string
1233
     *                      <p>A decoded MIME field on success,
1234
     *                      or false if an error occurs during the decoding.</p>
1235
     */
1236 2
    public static function decode_mimeheader($str, string $encoding = 'UTF-8')
1237
    {
1238 2
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
1239 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
1240
        }
1241
1242
        // always fallback via symfony polyfill
1243 2
        return \iconv_mime_decode($str, \ICONV_MIME_DECODE_CONTINUE_ON_ERROR, $encoding);
1244
    }
1245
1246
    /**
1247
     * Convert any two-letter country code (ISO 3166-1) to the corresponding Emoji.
1248
     *
1249
     * @see https://en.wikipedia.org/wiki/ISO_3166-1
1250
     *
1251
     * @param string $country_code_iso_3166_1 <p>e.g. DE</p>
1252
     *
1253
     * @return string
1254
     *                <p>Emoji or empty string on error.</p>
1255
     */
1256 1
    public static function emoji_from_country_code(string $country_code_iso_3166_1): string
1257
    {
1258 1
        if ($country_code_iso_3166_1 === '') {
1259 1
            return '';
1260
        }
1261
1262 1
        if (self::strlen($country_code_iso_3166_1) !== 2) {
1263 1
            return '';
1264
        }
1265
1266 1
        $country_code_iso_3166_1 = \strtoupper($country_code_iso_3166_1);
1267
1268 1
        $flagOffset = 0x1F1E6;
1269 1
        $asciiOffset = 0x41;
1270
1271 1
        return (self::chr((self::ord($country_code_iso_3166_1[0]) - $asciiOffset + $flagOffset)) ?? '') .
1272 1
               (self::chr((self::ord($country_code_iso_3166_1[1]) - $asciiOffset + $flagOffset)) ?? '');
1273
    }
1274
1275
    /**
1276
     * Decodes a string which was encoded by "UTF8::emoji_encode()".
1277
     *
1278
     * INFO: opposite to UTF8::emoji_encode()
1279
     *
1280
     * EXAMPLE: <code>
1281
     * UTF8::emoji_decode('foo CHARACTER_OGRE', false); // 'foo 👹'
1282
     * //
1283
     * UTF8::emoji_decode('foo _-_PORTABLE_UTF8_-_308095726_-_627590803_-_8FTU_ELBATROP_-_', true); // 'foo 👹'
1284
     * </code>
1285
     *
1286
     * @param string $str                            <p>The input string.</p>
1287
     * @param bool   $use_reversible_string_mappings [optional] <p>
1288
     *                                               When <b>TRUE</b>, we se a reversible string mapping
1289
     *                                               between "emoji_encode" and "emoji_decode".</p>
1290
     *
1291
     * @psalm-pure
1292
     *
1293
     * @return string
1294
     */
1295 9
    public static function emoji_decode(
1296
        string $str,
1297
        bool $use_reversible_string_mappings = false
1298
    ): string {
1299 9
        self::initEmojiData();
1300
1301 9
        if ($use_reversible_string_mappings) {
1302 9
            return (string) \str_replace(
1303 9
                (array) self::$EMOJI_KEYS_REVERSIBLE_CACHE,
1304 9
                (array) self::$EMOJI_VALUES_CACHE,
1305 9
                $str
1306
            );
1307
        }
1308
1309 1
        return (string) \str_replace(
1310 1
            (array) self::$EMOJI_KEYS_CACHE,
1311 1
            (array) self::$EMOJI_VALUES_CACHE,
1312 1
            $str
1313
        );
1314
    }
1315
1316
    /**
1317
     * Encode a string with emoji chars into a non-emoji string.
1318
     *
1319
     * INFO: opposite to UTF8::emoji_decode()
1320
     *
1321
     * EXAMPLE: <code>
1322
     * UTF8::emoji_encode('foo 👹', false)); // 'foo CHARACTER_OGRE'
1323
     * //
1324
     * UTF8::emoji_encode('foo 👹', true)); // 'foo _-_PORTABLE_UTF8_-_308095726_-_627590803_-_8FTU_ELBATROP_-_'
1325
     * </code>
1326
     *
1327
     * @param string $str                            <p>The input string</p>
1328
     * @param bool   $use_reversible_string_mappings [optional] <p>
1329
     *                                               when <b>TRUE</b>, we use a reversible string mapping
1330
     *                                               between "emoji_encode" and "emoji_decode"</p>
1331
     *
1332
     * @psalm-pure
1333
     *
1334
     * @return string
1335
     */
1336 12
    public static function emoji_encode(
1337
        string $str,
1338
        bool $use_reversible_string_mappings = false
1339
    ): string {
1340 12
        self::initEmojiData();
1341
1342 12
        if ($use_reversible_string_mappings) {
1343 9
            return (string) \str_replace(
1344 9
                (array) self::$EMOJI_VALUES_CACHE,
1345 9
                (array) self::$EMOJI_KEYS_REVERSIBLE_CACHE,
1346 9
                $str
1347
            );
1348
        }
1349
1350 4
        return (string) \str_replace(
1351 4
            (array) self::$EMOJI_VALUES_CACHE,
1352 4
            (array) self::$EMOJI_KEYS_CACHE,
1353 4
            $str
1354
        );
1355
    }
1356
1357
    /**
1358
     * Encode a string with a new charset-encoding.
1359
     *
1360
     * INFO:  This function will also try to fix broken / double encoding,
1361
     *        so you can call this function also on a UTF-8 string and you don't mess up the string.
1362
     *
1363
     * EXAMPLE: <code>
1364
     * UTF8::encode('ISO-8859-1', '-ABC-中文空白-'); // '-ABC-????-'
1365
     * //
1366
     * UTF8::encode('UTF-8', '-ABC-中文空白-'); // '-ABC-中文空白-'
1367
     * //
1368
     * UTF8::encode('HTML', '-ABC-中文空白-'); // '-ABC-&#20013;&#25991;&#31354;&#30333;-'
1369
     * //
1370
     * UTF8::encode('BASE64', '-ABC-中文空白-'); // 'LUFCQy3kuK3mlofnqbrnmb0t'
1371
     * </code>
1372
     *
1373
     * @param string $to_encoding                   <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.</p>
1374
     * @param string $str                           <p>The input string</p>
1375
     * @param bool   $auto_detect_the_from_encoding [optional] <p>Force the new encoding (we try to fix broken / double
1376
     *                                              encoding for UTF-8)<br> otherwise we auto-detect the current
1377
     *                                              string-encoding</p>
1378
     * @param string $from_encoding                 [optional] <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.<br>
1379
     *                                              A empty string will trigger the autodetect anyway.</p>
1380
     *
1381
     * @psalm-pure
1382
     *
1383
     * @return string
1384
     *
1385
     * @psalm-suppress InvalidReturnStatement
1386
     */
1387 29
    public static function encode(
1388
        string $to_encoding,
1389
        string $str,
1390
        bool $auto_detect_the_from_encoding = true,
1391
        string $from_encoding = ''
1392
    ): string {
1393 29
        if ($str === '' || $to_encoding === '') {
1394 13
            return $str;
1395
        }
1396
1397 29
        if ($to_encoding !== 'UTF-8' && $to_encoding !== 'CP850') {
1398 7
            $to_encoding = self::normalize_encoding($to_encoding, 'UTF-8');
1399
        }
1400
1401 29
        if ($from_encoding && $from_encoding !== 'UTF-8' && $from_encoding !== 'CP850') {
1402 2
            $from_encoding = self::normalize_encoding($from_encoding);
1403
        }
1404
1405
        if (
1406 29
            $to_encoding
1407
            &&
1408 29
            $from_encoding
1409
            &&
1410 29
            $from_encoding === $to_encoding
1411
        ) {
1412
            return $str;
1413
        }
1414
1415 29
        if ($to_encoding === 'JSON') {
1416 1
            $return = self::json_encode($str);
1417 1
            if ($return === false) {
1418
                throw new \InvalidArgumentException('The input string [' . $str . '] can not be used for json_encode().');
1419
            }
1420
1421 1
            return $return;
1422
        }
1423 29
        if ($from_encoding === 'JSON') {
1424 1
            $str = self::json_decode($str);
1425 1
            $from_encoding = '';
1426
        }
1427
1428 29
        if ($to_encoding === 'BASE64') {
1429 2
            return \base64_encode($str);
1430
        }
1431 29
        if ($from_encoding === 'BASE64') {
1432 2
            $str = \base64_decode($str, true);
1433 2
            $from_encoding = '';
1434
        }
1435
1436 29
        if ($to_encoding === 'HTML-ENTITIES') {
1437 2
            return self::html_encode($str, true);
1438
        }
1439 29
        if ($from_encoding === 'HTML-ENTITIES') {
1440 2
            $str = self::html_entity_decode($str, \ENT_COMPAT);
1441 2
            $from_encoding = '';
1442
        }
1443
1444 29
        $from_encoding_auto_detected = false;
1445
        if (
1446 29
            $auto_detect_the_from_encoding
1447
            ||
1448 29
            !$from_encoding
1449
        ) {
1450 29
            $from_encoding_auto_detected = self::str_detect_encoding($str);
1451
        }
1452
1453
        // DEBUG
1454
        //var_dump($to_encoding, $from_encoding, $from_encoding_auto_detected, $str, "\n\n");
1455
1456 29
        if ($from_encoding_auto_detected !== false) {
1457
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
1458 25
            $from_encoding = $from_encoding_auto_detected;
1459 7
        } elseif ($auto_detect_the_from_encoding) {
1460
            // fallback for the "autodetect"-mode
1461 7
            return self::to_utf8($str);
1462
        }
1463
1464
        if (
1465 25
            !$from_encoding
1466
            ||
1467 25
            $from_encoding === $to_encoding
1468
        ) {
1469 15
            return $str;
1470
        }
1471
1472
        if (
1473 20
            $to_encoding === 'UTF-8'
1474
            &&
1475
            (
1476 18
                $from_encoding === 'WINDOWS-1252'
1477
                ||
1478 20
                $from_encoding === 'ISO-8859-1'
1479
            )
1480
        ) {
1481 14
            return self::to_utf8($str);
1482
        }
1483
1484
        if (
1485 12
            $to_encoding === 'ISO-8859-1'
1486
            &&
1487
            (
1488 6
                $from_encoding === 'WINDOWS-1252'
1489
                ||
1490 12
                $from_encoding === 'UTF-8'
1491
            )
1492
        ) {
1493 6
            return self::to_iso8859($str);
1494
        }
1495
1496
        /** @noinspection InArrayCanBeUsedInspection */
1497
        if (
1498 10
            $to_encoding !== 'UTF-8'
1499
            &&
1500 10
            $to_encoding !== 'ISO-8859-1'
1501
            &&
1502 10
            $to_encoding !== 'WINDOWS-1252'
1503
            &&
1504 10
            self::$SUPPORT['mbstring'] === false
1505
        ) {
1506
            /**
1507
             * @psalm-suppress ImpureFunctionCall - is is only a warning
1508
             */
1509
            \trigger_error('UTF8::encode() without mbstring cannot handle "' . $to_encoding . '" encoding', \E_USER_WARNING);
1510
        }
1511
1512 10
        if (self::$SUPPORT['mbstring'] === true) {
1513
            // warning: do not use the symfony polyfill here
1514 10
            $str_encoded = \mb_convert_encoding(
1515 10
                $str,
1516 10
                $to_encoding,
1517 10
                $from_encoding
1518
            );
1519
1520 10
            if ($str_encoded) {
1521 10
                \assert(\is_string($str_encoded));
1522
1523 10
                return $str_encoded;
1524
            }
1525
        }
1526
1527
        /** @noinspection PhpUsageOfSilenceOperatorInspection - Detected an incomplete multibyte character in input string */
1528
        $return = @\iconv($from_encoding, $to_encoding, $str);
1529
        if ($return !== false) {
1530
            return $return;
1531
        }
1532
1533
        return $str;
1534
    }
1535
1536
    /**
1537
     * @param string $str
1538
     * @param string $from_charset      [optional] <p>Set the input charset.</p>
1539
     * @param string $to_charset        [optional] <p>Set the output charset.</p>
1540
     * @param string $transfer_encoding [optional] <p>Set the transfer encoding.</p>
1541
     * @param string $linefeed          [optional] <p>Set the used linefeed.</p>
1542
     * @param int    $indent            [optional] <p>Set the max length indent.</p>
1543
     *
1544
     * @psalm-pure
1545
     *
1546
     * @return false|string
1547
     *                      <p>An encoded MIME field on success,
1548
     *                      or false if an error occurs during the encoding.</p>
1549
     */
1550 1
    public static function encode_mimeheader(
1551
        string $str,
1552
        string $from_charset = 'UTF-8',
1553
        string $to_charset = 'UTF-8',
1554
        string $transfer_encoding = 'Q',
1555
        string $linefeed = "\r\n",
1556
        int $indent = 76
1557
    ) {
1558 1
        if ($from_charset !== 'UTF-8' && $from_charset !== 'CP850') {
1559
            $from_charset = self::normalize_encoding($from_charset, 'UTF-8');
1560
        }
1561
1562 1
        if ($to_charset !== 'UTF-8' && $to_charset !== 'CP850') {
1563 1
            $to_charset = self::normalize_encoding($to_charset, 'UTF-8');
1564
        }
1565
1566
        // always fallback via symfony polyfill
1567 1
        return \iconv_mime_encode(
1568 1
            '',
1569 1
            $str,
1570
            [
1571 1
                'scheme'           => $transfer_encoding,
1572 1
                'line-length'      => $indent,
1573 1
                'input-charset'    => $from_charset,
1574 1
                'output-charset'   => $to_charset,
1575 1
                'line-break-chars' => $linefeed,
1576
            ]
1577
        );
1578
    }
1579
1580
    /**
1581
     * Create an extract from a sentence, so if the search-string was found, it try to centered in the output.
1582
     *
1583
     * @param string   $str                       <p>The input string.</p>
1584
     * @param string   $search                    <p>The searched string.</p>
1585
     * @param int|null $length                    [optional] <p>Default: null === text->length / 2</p>
1586
     * @param string   $replacer_for_skipped_text [optional] <p>Default: …</p>
1587
     * @param string   $encoding                  [optional] <p>Set the charset for e.g. "mb_" function</p>
1588
     *
1589
     * @psalm-pure
1590
     *
1591
     * @return string
1592
     */
1593 1
    public static function extract_text(
1594
        string $str,
1595
        string $search = '',
1596
        int $length = null,
1597
        string $replacer_for_skipped_text = '…',
1598
        string $encoding = 'UTF-8'
1599
    ): string {
1600 1
        if ($str === '') {
1601 1
            return '';
1602
        }
1603
1604 1
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
1605
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
1606
        }
1607
1608 1
        $trim_chars = "\t\r\n -_()!~?=+/*\\,.:;\"'[]{}`&";
1609
1610 1
        if ($length === null) {
1611 1
            $length = (int) \round((int) self::strlen($str, $encoding) / 2);
1612
        }
1613
1614 1
        if ($search === '') {
1615 1
            if ($encoding === 'UTF-8') {
1616 1
                if ($length > 0) {
1617 1
                    $string_length = (int) \mb_strlen($str);
1618 1
                    $end = ($length - 1) > $string_length ? $string_length : ($length - 1);
1619
                } else {
1620 1
                    $end = 0;
1621
                }
1622
1623 1
                $pos = (int) \min(
1624 1
                    \mb_strpos($str, ' ', $end),
1625 1
                    \mb_strpos($str, '.', $end)
1626
                );
1627
            } else {
1628
                if ($length > 0) {
1629
                    $string_length = (int) self::strlen($str, $encoding);
1630
                    $end = ($length - 1) > $string_length ? $string_length : ($length - 1);
1631
                } else {
1632
                    $end = 0;
1633
                }
1634
1635
                $pos = (int) \min(
1636
                    self::strpos($str, ' ', $end, $encoding),
1637
                    self::strpos($str, '.', $end, $encoding)
1638
                );
1639
            }
1640
1641 1
            if ($pos) {
1642 1
                if ($encoding === 'UTF-8') {
1643 1
                    $str_sub = \mb_substr($str, 0, $pos);
1644
                } else {
1645
                    $str_sub = self::substr($str, 0, $pos, $encoding);
1646
                }
1647
1648 1
                if ($str_sub === false) {
1649
                    return '';
1650
                }
1651
1652 1
                return \rtrim($str_sub, $trim_chars) . $replacer_for_skipped_text;
1653
            }
1654
1655
            return $str;
1656
        }
1657
1658 1
        if ($encoding === 'UTF-8') {
1659 1
            $word_position = (int) \mb_stripos($str, $search);
1660 1
            $half_side = (int) ($word_position - $length / 2 + (int) \mb_strlen($search) / 2);
1661
        } else {
1662
            $word_position = (int) self::stripos($str, $search, 0, $encoding);
1663
            $half_side = (int) ($word_position - $length / 2 + (int) self::strlen($search, $encoding) / 2);
1664
        }
1665
1666 1
        $pos_start = 0;
1667 1
        if ($half_side > 0) {
1668 1
            if ($encoding === 'UTF-8') {
1669 1
                $half_text = \mb_substr($str, 0, $half_side);
1670
            } else {
1671
                $half_text = self::substr($str, 0, $half_side, $encoding);
1672
            }
1673 1
            if ($half_text !== false) {
1674 1
                if ($encoding === 'UTF-8') {
1675 1
                    $pos_start = (int) \max(
1676 1
                        \mb_strrpos($half_text, ' '),
1677 1
                        \mb_strrpos($half_text, '.')
1678
                    );
1679
                } else {
1680
                    $pos_start = (int) \max(
1681
                        self::strrpos($half_text, ' ', 0, $encoding),
1682
                        self::strrpos($half_text, '.', 0, $encoding)
1683
                    );
1684
                }
1685
            }
1686
        }
1687
1688 1
        if ($word_position && $half_side > 0) {
1689 1
            $offset = $pos_start + $length - 1;
1690 1
            $real_length = (int) self::strlen($str, $encoding);
1691
1692 1
            if ($offset > $real_length) {
1693
                $offset = $real_length;
1694
            }
1695
1696 1
            if ($encoding === 'UTF-8') {
1697 1
                $pos_end = (int) \min(
1698 1
                    \mb_strpos($str, ' ', $offset),
1699 1
                    \mb_strpos($str, '.', $offset)
1700 1
                ) - $pos_start;
1701
            } else {
1702
                $pos_end = (int) \min(
1703
                    self::strpos($str, ' ', $offset, $encoding),
1704
                    self::strpos($str, '.', $offset, $encoding)
1705
                ) - $pos_start;
1706
            }
1707
1708 1
            if (!$pos_end || $pos_end <= 0) {
1709 1
                if ($encoding === 'UTF-8') {
1710 1
                    $str_sub = \mb_substr($str, $pos_start, (int) \mb_strlen($str));
1711
                } else {
1712
                    $str_sub = self::substr($str, $pos_start, (int) self::strlen($str, $encoding), $encoding);
1713
                }
1714 1
                if ($str_sub !== false) {
1715 1
                    $extract = $replacer_for_skipped_text . \ltrim($str_sub, $trim_chars);
1716
                } else {
1717 1
                    $extract = '';
1718
                }
1719
            } else {
1720 1
                if ($encoding === 'UTF-8') {
1721 1
                    $str_sub = \mb_substr($str, $pos_start, $pos_end);
1722
                } else {
1723
                    $str_sub = self::substr($str, $pos_start, $pos_end, $encoding);
1724
                }
1725 1
                if ($str_sub !== false) {
1726 1
                    $extract = $replacer_for_skipped_text . \trim($str_sub, $trim_chars) . $replacer_for_skipped_text;
1727
                } else {
1728 1
                    $extract = '';
1729
                }
1730
            }
1731
        } else {
1732 1
            $offset = $length - 1;
1733 1
            $true_length = (int) self::strlen($str, $encoding);
1734
1735 1
            if ($offset > $true_length) {
1736
                $offset = $true_length;
1737
            }
1738
1739 1
            if ($encoding === 'UTF-8') {
1740 1
                $pos_end = (int) \min(
1741 1
                    \mb_strpos($str, ' ', $offset),
1742 1
                    \mb_strpos($str, '.', $offset)
1743
                );
1744
            } else {
1745
                $pos_end = (int) \min(
1746
                    self::strpos($str, ' ', $offset, $encoding),
1747
                    self::strpos($str, '.', $offset, $encoding)
1748
                );
1749
            }
1750
1751 1
            if ($pos_end) {
1752 1
                if ($encoding === 'UTF-8') {
1753 1
                    $str_sub = \mb_substr($str, 0, $pos_end);
1754
                } else {
1755
                    $str_sub = self::substr($str, 0, $pos_end, $encoding);
1756
                }
1757 1
                if ($str_sub !== false) {
1758 1
                    $extract = \rtrim($str_sub, $trim_chars) . $replacer_for_skipped_text;
1759
                } else {
1760 1
                    $extract = '';
1761
                }
1762
            } else {
1763 1
                $extract = $str;
1764
            }
1765
        }
1766
1767 1
        return $extract;
1768
    }
1769
1770
    /**
1771
     * Reads entire file into a string.
1772
     *
1773
     * EXAMPLE: <code>UTF8::file_get_contents('utf16le.txt'); // ...</code>
1774
     *
1775
     * WARNING: Do not use UTF-8 Option ($convert_to_utf8) for binary files (e.g.: images) !!!
1776
     *
1777
     * @see http://php.net/manual/en/function.file-get-contents.php
1778
     *
1779
     * @param string        $filename         <p>
1780
     *                                        Name of the file to read.
1781
     *                                        </p>
1782
     * @param bool          $use_include_path [optional] <p>
1783
     *                                        Prior to PHP 5, this parameter is called
1784
     *                                        use_include_path and is a bool.
1785
     *                                        As of PHP 5 the FILE_USE_INCLUDE_PATH can be used
1786
     *                                        to trigger include path
1787
     *                                        search.
1788
     *                                        </p>
1789
     * @param resource|null $context          [optional] <p>
1790
     *                                        A valid context resource created with
1791
     *                                        stream_context_create. If you don't need to use a
1792
     *                                        custom context, you can skip this parameter by &null;.
1793
     *                                        </p>
1794
     * @param int|null      $offset           [optional] <p>
1795
     *                                        The offset where the reading starts.
1796
     *                                        </p>
1797
     * @param int|null      $max_length       [optional] <p>
1798
     *                                        Maximum length of data read. The default is to read until end
1799
     *                                        of file is reached.
1800
     *                                        </p>
1801
     * @param int           $timeout          <p>The time in seconds for the timeout.</p>
1802
     * @param bool          $convert_to_utf8  <strong>WARNING!!!</strong> <p>Maybe you can't use this option for
1803
     *                                        some files, because they used non default utf-8 chars. Binary files
1804
     *                                        like images or pdf will not be converted.</p>
1805
     * @param string        $from_encoding    [optional] <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.<br>
1806
     *                                        A empty string will trigger the autodetect anyway.</p>
1807
     *
1808
     * @psalm-pure
1809
     *
1810
     * @return false|string
1811
     *                      <p>The function returns the read data as string or <b>false</b> on failure.</p>
1812
     *
1813
     * @noinspection PhpTooManyParametersInspection
1814
     */
1815 12
    public static function file_get_contents(
1816
        string $filename,
1817
        bool $use_include_path = false,
1818
        $context = null,
1819
        int $offset = null,
1820
        int $max_length = null,
1821
        int $timeout = 10,
1822
        bool $convert_to_utf8 = true,
1823
        string $from_encoding = ''
1824
    ) {
1825
        // init
1826 12
        $filename = \filter_var($filename, \FILTER_SANITIZE_STRING);
1827
        /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
1828 12
        if ($filename === false) {
1829
            return false;
1830
        }
1831
1832 12
        if ($timeout && $context === null) {
1833 9
            $context = \stream_context_create(
1834
                [
1835
                    'http' => [
1836 9
                        'timeout' => $timeout,
1837
                    ],
1838
                ]
1839
            );
1840
        }
1841
1842 12
        if ($offset === null) {
1843 12
            $offset = 0;
1844
        }
1845
1846 12
        if (\is_int($max_length)) {
1847 2
            $data = \file_get_contents($filename, $use_include_path, $context, $offset, $max_length);
1848
        } else {
1849 12
            $data = \file_get_contents($filename, $use_include_path, $context, $offset);
1850
        }
1851
1852
        // return false on error
1853 12
        if ($data === false) {
1854
            return false;
1855
        }
1856
1857 12
        if ($convert_to_utf8) {
1858
            if (
1859 12
                !self::is_binary($data, true)
1860
                ||
1861 9
                self::is_utf16($data, false) !== false
1862
                ||
1863 12
                self::is_utf32($data, false) !== false
1864
            ) {
1865 9
                $data = self::encode('UTF-8', $data, false, $from_encoding);
1866 9
                $data = self::cleanup($data);
1867
            }
1868
        }
1869
1870 12
        return $data;
1871
    }
1872
1873
    /**
1874
     * Checks if a file starts with BOM (Byte Order Mark) character.
1875
     *
1876
     * EXAMPLE: <code>UTF8::file_has_bom('utf8_with_bom.txt'); // true</code>
1877
     *
1878
     * @param string $file_path <p>Path to a valid file.</p>
1879
     *
1880
     * @throws \RuntimeException if file_get_contents() returned false
1881
     *
1882
     * @return bool
1883
     *              <p><strong>true</strong> if the file has BOM at the start, <strong>false</strong> otherwise</p>
1884
     *
1885
     * @psalm-pure
1886
     */
1887 2
    public static function file_has_bom(string $file_path): bool
1888
    {
1889 2
        $file_content = \file_get_contents($file_path);
1890 2
        if ($file_content === false) {
1891
            throw new \RuntimeException('file_get_contents() returned false for:' . $file_path);
1892
        }
1893
1894 2
        return self::string_has_bom($file_content);
1895
    }
1896
1897
    /**
1898
     * Normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1899
     *
1900
     * EXAMPLE: <code>UTF8::filter(array("\xE9", 'à', 'a')); // array('é', 'à', 'a')</code>
1901
     *
1902
     * @param array|object|string $var
1903
     * @param int                 $normalization_form
1904
     * @param string              $leading_combining
1905
     *
1906
     * @psalm-pure
1907
     *
1908
     * @return mixed
1909
     *
1910
     * @template TFilter
1911
     * @phpstan-param TFilter $var
1912
     * @phpstan-return TFilter
1913
     */
1914 65
    public static function filter(
1915
        $var,
1916
        int $normalization_form = \Normalizer::NFC,
1917
        string $leading_combining = '◌'
1918
    ) {
1919 65
        switch (\gettype($var)) {
1920 65
            case 'object':
1921 65
            case 'array':
1922 6
                foreach ($var as $k => &$v) {
1923 6
                    $v = self::filter($v, $normalization_form, $leading_combining);
1924
                }
1925 6
                unset($v);
1926
1927 6
                break;
1928 65
            case 'string':
1929
1930 63
                if (\strpos($var, "\r") !== false) {
1931 3
                    $var = self::normalize_line_ending($var);
1932
                }
1933
1934 63
                if (!ASCII::is_ascii($var)) {
1935 33
                    if (\Normalizer::isNormalized($var, $normalization_form)) {
1936 27
                        $n = '-';
1937
                    } else {
1938 13
                        $n = \Normalizer::normalize($var, $normalization_form);
1939
1940 13
                        if (isset($n[0])) {
1941 7
                            $var = $n;
1942
                        } else {
1943 9
                            $var = self::encode('UTF-8', $var);
1944
                        }
1945
                    }
1946
1947 33
                    \assert(\is_string($var));
1948
                    if (
1949 33
                        $var[0] >= "\x80"
1950
                        &&
1951 33
                        isset($n[0], $leading_combining[0])
1952
                        &&
1953 33
                        \preg_match('/^\\p{Mn}/u', $var)
1954
                    ) {
1955
                        // Prevent leading combining chars
1956
                        // for NFC-safe concatenations.
1957 3
                        $var = $leading_combining . $var;
1958
                    }
1959
                }
1960
1961 63
                break;
1962
            default:
1963
                // nothing
1964
        }
1965
1966
        /** @noinspection PhpSillyAssignmentInspection */
1967
        /** @phpstan-var TFilter $var */
1968 65
        $var = $var;
1969
1970 65
        return $var;
1971
    }
1972
1973
    /**
1974
     * "filter_input()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1975
     *
1976
     * Gets a specific external variable by name and optionally filters it.
1977
     *
1978
     * EXAMPLE: <code>
1979
     * // _GET['foo'] = 'bar';
1980
     * UTF8::filter_input(INPUT_GET, 'foo', FILTER_SANITIZE_STRING)); // 'bar'
1981
     * </code>
1982
     *
1983
     * @see http://php.net/manual/en/function.filter-input.php
1984
     *
1985
     * @param int            $type          <p>
1986
     *                                      One of <b>INPUT_GET</b>, <b>INPUT_POST</b>,
1987
     *                                      <b>INPUT_COOKIE</b>, <b>INPUT_SERVER</b>, or
1988
     *                                      <b>INPUT_ENV</b>.
1989
     *                                      </p>
1990
     * @param string         $variable_name <p>
1991
     *                                      Name of a variable to get.
1992
     *                                      </p>
1993
     * @param int            $filter        [optional] <p>
1994
     *                                      The ID of the filter to apply. The
1995
     *                                      manual page lists the available filters.
1996
     *                                      </p>
1997
     * @param int|int[]|null $options       [optional] <p>
1998
     *                                      Associative array of options or bitwise disjunction of flags. If filter
1999
     *                                      accepts options, flags can be provided in "flags" field of array.
2000
     *                                      </p>
2001
     *
2002
     * @psalm-pure
2003
     *
2004
     * @return mixed
2005
     *               <p>
2006
     *               Value of the requested variable on success, <b>FALSE</b> if the filter fails, or <b>NULL</b> if the
2007
     *               <i>variable_name</i> variable is not set. If the flag <b>FILTER_NULL_ON_FAILURE</b> is used, it
2008
     *               returns <b>FALSE</b> if the variable is not set and <b>NULL</b> if the filter fails.
2009
     *               </p>
2010
     */
2011 1
    public static function filter_input(
2012
        int $type,
2013
        string $variable_name,
2014
        int $filter = \FILTER_DEFAULT,
2015
        $options = null
2016
    ) {
2017
        /**
2018
         * @psalm-suppress ImpureFunctionCall - we use func_num_args only for args count matching here
2019
         */
2020 1
        if ($options === null || \func_num_args() < 4) {
2021 1
            $var = \filter_input($type, $variable_name, $filter);
2022
        } else {
2023
            $var = \filter_input($type, $variable_name, $filter, $options);
2024
        }
2025
2026 1
        return self::filter($var);
2027
    }
2028
2029
    /**
2030
     * "filter_input_array()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
2031
     *
2032
     * Gets external variables and optionally filters them.
2033
     *
2034
     * EXAMPLE: <code>
2035
     * // _GET['foo'] = 'bar';
2036
     * UTF8::filter_input_array(INPUT_GET, array('foo' => 'FILTER_SANITIZE_STRING')); // array('bar')
2037
     * </code>
2038
     *
2039
     * @see http://php.net/manual/en/function.filter-input-array.php
2040
     *
2041
     * @param int        $type       <p>
2042
     *                               One of <b>INPUT_GET</b>, <b>INPUT_POST</b>,
2043
     *                               <b>INPUT_COOKIE</b>, <b>INPUT_SERVER</b>, or
2044
     *                               <b>INPUT_ENV</b>.
2045
     *                               </p>
2046
     * @param array|null $definition [optional] <p>
2047
     *                               An array defining the arguments. A valid key is a string
2048
     *                               containing a variable name and a valid value is either a filter type, or an array
2049
     *                               optionally specifying the filter, flags and options. If the value is an
2050
     *                               array, valid keys are filter which specifies the
2051
     *                               filter type,
2052
     *                               flags which specifies any flags that apply to the
2053
     *                               filter, and options which specifies any options that
2054
     *                               apply to the filter. See the example below for a better understanding.
2055
     *                               </p>
2056
     *                               <p>
2057
     *                               This parameter can be also an integer holding a filter constant. Then all values in the
2058
     *                               input array are filtered by this filter.
2059
     *                               </p>
2060
     * @param bool       $add_empty  [optional] <p>
2061
     *                               Add missing keys as <b>NULL</b> to the return value.
2062
     *                               </p>
2063
     *
2064
     * @psalm-pure
2065
     *
2066
     * @return mixed
2067
     *               <p>
2068
     *               An array containing the values of the requested variables on success, or <b>FALSE</b> on failure.
2069
     *               An array value will be <b>FALSE</b> if the filter fails, or <b>NULL</b> if the variable is not
2070
     *               set. Or if the flag <b>FILTER_NULL_ON_FAILURE</b> is used, it returns <b>FALSE</b> if the variable
2071
     *               is not set and <b>NULL</b> if the filter fails.
2072
     *               </p>
2073
     */
2074 1
    public static function filter_input_array(
2075
        int $type,
2076
        $definition = null,
2077
        bool $add_empty = true
2078
    ) {
2079
        /**
2080
         * @psalm-suppress ImpureFunctionCall - we use func_num_args only for args count matching here
2081
         */
2082 1
        if ($definition === null || \func_num_args() < 2) {
2083
            $a = \filter_input_array($type);
2084
        } else {
2085 1
            $a = \filter_input_array($type, $definition, $add_empty);
2086
        }
2087
2088 1
        return self::filter($a);
2089
    }
2090
2091
    /**
2092
     * "filter_var()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
2093
     *
2094
     * Filters a variable with a specified filter.
2095
     *
2096
     * EXAMPLE: <code>UTF8::filter_var('-ABC-中文空白-', FILTER_VALIDATE_URL); // false</code>
2097
     *
2098
     * @see http://php.net/manual/en/function.filter-var.php
2099
     *
2100
     * @param float|int|string|null $variable <p>
2101
     *                                        Value to filter.
2102
     *                                        </p>
2103
     * @param int                   $filter   [optional] <p>
2104
     *                                        The ID of the filter to apply. The
2105
     *                                        manual page lists the available filters.
2106
     *                                        </p>
2107
     * @param int|int[]|null        $options  [optional] <p>
2108
     *                                        Associative array of options or bitwise disjunction of flags. If filter
2109
     *                                        accepts options, flags can be provided in "flags" field of array. For
2110
     *                                        the "callback" filter, callable type should be passed. The
2111
     *                                        callback must accept one argument, the value to be filtered, and return
2112
     *                                        the value after filtering/sanitizing it.
2113
     *                                        </p>
2114
     *                                        <p>
2115
     *                                        <code>
2116
     *                                        // for filters that accept options, use this format
2117
     *                                        $options = array(
2118
     *                                        'options' => array(
2119
     *                                        'default' => 3, // value to return if the filter fails
2120
     *                                        // other options here
2121
     *                                        'min_range' => 0
2122
     *                                        ),
2123
     *                                        'flags' => FILTER_FLAG_ALLOW_OCTAL,
2124
     *                                        );
2125
     *                                        $var = filter_var('0755', FILTER_VALIDATE_INT, $options);
2126
     *                                        // for filter that only accept flags, you can pass them directly
2127
     *                                        $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
2128
     *                                        // for filter that only accept flags, you can also pass as an array
2129
     *                                        $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
2130
     *                                        array('flags' => FILTER_NULL_ON_FAILURE));
2131
     *                                        // callback validate filter
2132
     *                                        function foo($value)
2133
     *                                        {
2134
     *                                        // Expected format: Surname, GivenNames
2135
     *                                        if (strpos($value, ", ") === false) return false;
2136
     *                                        list($surname, $givennames) = explode(", ", $value, 2);
2137
     *                                        $empty = (empty($surname) || empty($givennames));
2138
     *                                        $notstrings = (!is_string($surname) || !is_string($givennames));
2139
     *                                        if ($empty || $notstrings) {
2140
     *                                        return false;
2141
     *                                        } else {
2142
     *                                        return $value;
2143
     *                                        }
2144
     *                                        }
2145
     *                                        $var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));
2146
     *                                        </code>
2147
     *                                        </p>
2148
     *
2149
     * @psalm-pure
2150
     *
2151
     * @return mixed
2152
     *               <p>The filtered data, or <b>FALSE</b> if the filter fails.</p>
2153
     */
2154 2
    public static function filter_var(
2155
        $variable,
2156
        int $filter = \FILTER_DEFAULT,
2157
        $options = null
2158
    ) {
2159
        /**
2160
         * @psalm-suppress ImpureFunctionCall - we use func_num_args only for args count matching here
2161
         */
2162 2
        if (\func_num_args() < 3) {
2163 2
            $variable = \filter_var($variable, $filter);
2164
        } else {
2165 2
            $variable = \filter_var($variable, $filter, $options);
2166
        }
2167
2168 2
        return self::filter($variable);
2169
    }
2170
2171
    /**
2172
     * "filter_var_array()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
2173
     *
2174
     * Gets multiple variables and optionally filters them.
2175
     *
2176
     * EXAMPLE: <code>
2177
     * $filters = [
2178
     *     'name'  => ['filter'  => FILTER_CALLBACK, 'options' => [UTF8::class, 'ucwords']],
2179
     *     'age'   => ['filter'  => FILTER_VALIDATE_INT, 'options' => ['min_range' => 1, 'max_range' => 120]],
2180
     *     'email' => FILTER_VALIDATE_EMAIL,
2181
     * ];
2182
     *
2183
     * $data = [
2184
     *     'name' => 'κόσμε',
2185
     *     'age' => '18',
2186
     *     'email' => '[email protected]'
2187
     * ];
2188
     *
2189
     * UTF8::filter_var_array($data, $filters, true); // ['name' => 'Κόσμε', 'age' => 18, 'email' => '[email protected]']
2190
     * </code>
2191
     *
2192
     * @see http://php.net/manual/en/function.filter-var-array.php
2193
     *
2194
     * @param array<mixed>   $data       <p>
2195
     *                                   An array with string keys containing the data to filter.
2196
     *                                   </p>
2197
     * @param array|int|null $definition [optional] <p>
2198
     *                                   An array defining the arguments. A valid key is a string
2199
     *                                   containing a variable name and a valid value is either a
2200
     *                                   filter type, or an
2201
     *                                   array optionally specifying the filter, flags and options.
2202
     *                                   If the value is an array, valid keys are filter
2203
     *                                   which specifies the filter type,
2204
     *                                   flags which specifies any flags that apply to the
2205
     *                                   filter, and options which specifies any options that
2206
     *                                   apply to the filter. See the example below for a better understanding.
2207
     *                                   </p>
2208
     *                                   <p>
2209
     *                                   This parameter can be also an integer holding a filter constant. Then all values
2210
     *                                   in the input array are filtered by this filter.
2211
     *                                   </p>
2212
     * @param bool           $add_empty  [optional] <p>
2213
     *                                   Add missing keys as <b>NULL</b> to the return value.
2214
     *                                   </p>
2215
     *
2216
     * @psalm-pure
2217
     *
2218
     * @return mixed
2219
     *               <p>
2220
     *               An array containing the values of the requested variables on success, or <b>FALSE</b> on failure.
2221
     *               An array value will be <b>FALSE</b> if the filter fails, or <b>NULL</b> if the variable is not
2222
     *               set.
2223
     *               </p>
2224
     */
2225 2
    public static function filter_var_array(
2226
        array $data,
2227
        $definition = null,
2228
        bool $add_empty = true
2229
    ) {
2230
        /**
2231
         * @psalm-suppress ImpureFunctionCall - we use func_num_args only for args count matching here
2232
         */
2233 2
        if (\func_num_args() < 2) {
2234 2
            $a = \filter_var_array($data);
2235
        } else {
2236 2
            $a = \filter_var_array($data, $definition, $add_empty);
2237
        }
2238
2239 2
        return self::filter($a);
2240
    }
2241
2242
    /**
2243
     * Checks whether finfo is available on the server.
2244
     *
2245
     * @psalm-pure
2246
     *
2247
     * @return bool
2248
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
2249
     *
2250
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
2251
     */
2252
    public static function finfo_loaded(): bool
2253
    {
2254
        return \class_exists('finfo');
2255
    }
2256
2257
    /**
2258
     * Returns the first $n characters of the string.
2259
     *
2260
     * @param string $str      <p>The input string.</p>
2261
     * @param int    $n        <p>Number of characters to retrieve from the start.</p>
2262
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
2263
     *
2264
     * @psalm-pure
2265
     *
2266
     * @return string
2267
     */
2268 13
    public static function first_char(
2269
        string $str,
2270
        int $n = 1,
2271
        string $encoding = 'UTF-8'
2272
    ): string {
2273 13
        if ($str === '' || $n <= 0) {
2274 5
            return '';
2275
        }
2276
2277 8
        if ($encoding === 'UTF-8') {
2278 4
            return (string) \mb_substr($str, 0, $n);
2279
        }
2280
2281 4
        return (string) self::substr($str, 0, $n, $encoding);
2282
    }
2283
2284
    /**
2285
     * Check if the number of Unicode characters isn't greater than the specified integer.
2286
     *
2287
     * EXAMPLE: <code>UTF8::fits_inside('κόσμε', 6); // false</code>
2288
     *
2289
     * @param string $str      the original string to be checked
2290
     * @param int    $box_size the size in number of chars to be checked against string
2291
     *
2292
     * @psalm-pure
2293
     *
2294
     * @return bool
2295
     *              <p><strong>TRUE</strong> if string is less than or equal to $box_size, <strong>FALSE</strong> otherwise.</p>
2296
     */
2297 2
    public static function fits_inside(string $str, int $box_size): bool
2298
    {
2299 2
        return (int) self::strlen($str) <= $box_size;
2300
    }
2301
2302
    /**
2303
     * Try to fix simple broken UTF-8 strings.
2304
     *
2305
     * INFO: Take a look at "UTF8::fix_utf8()" if you need a more advanced fix for broken UTF-8 strings.
2306
     *
2307
     * EXAMPLE: <code>UTF8::fix_simple_utf8('Düsseldorf'); // 'Düsseldorf'</code>
2308
     *
2309
     * If you received an UTF-8 string that was converted from Windows-1252 as it was ISO-8859-1
2310
     * (ignoring Windows-1252 chars from 80 to 9F) use this function to fix it.
2311
     * See: http://en.wikipedia.org/wiki/Windows-1252
2312
     *
2313
     * @param string $str <p>The input string</p>
2314
     *
2315
     * @psalm-pure
2316
     *
2317
     * @return string
2318
     */
2319 47
    public static function fix_simple_utf8(string $str): string
2320
    {
2321 47
        if ($str === '') {
2322 4
            return '';
2323
        }
2324
2325
        /**
2326
         * @psalm-suppress ImpureStaticVariable
2327
         *
2328
         * @var array<mixed>|null
2329
         */
2330 47
        static $BROKEN_UTF8_TO_UTF8_KEYS_CACHE = null;
2331
2332
        /**
2333
         * @psalm-suppress ImpureStaticVariable
2334
         *
2335
         * @var array<mixed>|null
2336
         */
2337 47
        static $BROKEN_UTF8_TO_UTF8_VALUES_CACHE = null;
2338
2339 47
        if ($BROKEN_UTF8_TO_UTF8_KEYS_CACHE === null) {
2340 1
            if (self::$BROKEN_UTF8_FIX === null) {
2341 1
                self::$BROKEN_UTF8_FIX = self::getData('utf8_fix');
2342
            }
2343
2344 1
            $BROKEN_UTF8_TO_UTF8_KEYS_CACHE = \array_keys(self::$BROKEN_UTF8_FIX);
2345 1
            $BROKEN_UTF8_TO_UTF8_VALUES_CACHE = self::$BROKEN_UTF8_FIX;
2346
        }
2347
2348 47
        \assert(\is_array($BROKEN_UTF8_TO_UTF8_VALUES_CACHE));
2349
2350 47
        return \str_replace($BROKEN_UTF8_TO_UTF8_KEYS_CACHE, $BROKEN_UTF8_TO_UTF8_VALUES_CACHE, $str);
2351
    }
2352
2353
    /**
2354
     * Fix a double (or multiple) encoded UTF8 string.
2355
     *
2356
     * EXAMPLE: <code>UTF8::fix_utf8('Fédération'); // 'Fédération'</code>
2357
     *
2358
     * @param string|string[] $str you can use a string or an array of strings
2359
     *
2360
     * @psalm-pure
2361
     *
2362
     * @return string|string[]
2363
     *                         Will return the fixed input-"array" or
2364
     *                         the fixed input-"string"
2365
     *
2366
     * @psalm-suppress InvalidReturnType
2367
     */
2368 2
    public static function fix_utf8($str)
2369
    {
2370 2
        if (\is_array($str)) {
2371 2
            foreach ($str as $k => &$v) {
2372 2
                $v = self::fix_utf8($v);
2373
            }
2374 2
            unset($v);
2375
2376
            /**
2377
             * @psalm-suppress InvalidReturnStatement
2378
             */
2379 2
            return $str;
2380
        }
2381
2382 2
        $str = (string) $str;
2383 2
        $last = '';
2384 2
        while ($last !== $str) {
2385 2
            $last = $str;
2386
            /**
2387
             * @psalm-suppress PossiblyInvalidArgument
2388
             */
2389 2
            $str = self::to_utf8(
2390 2
                self::utf8_decode($str, true)
2391
            );
2392
        }
2393
2394
        /**
2395
         * @psalm-suppress InvalidReturnStatement
2396
         */
2397 2
        return $str;
2398
    }
2399
2400
    /**
2401
     * Get character of a specific character.
2402
     *
2403
     * EXAMPLE: <code>UTF8::getCharDirection('ا'); // 'RTL'</code>
2404
     *
2405
     * @param string $char
2406
     *
2407
     * @psalm-pure
2408
     *
2409
     * @return string
2410
     *                <p>'RTL' or 'LTR'.</p>
2411
     */
2412 2
    public static function getCharDirection(string $char): string
2413
    {
2414 2
        if (self::$SUPPORT['intlChar'] === true) {
2415
            /** @noinspection PhpComposerExtensionStubsInspection */
2416 2
            $tmp_return = \IntlChar::charDirection($char);
2417
2418
            // from "IntlChar"-Class
2419
            $char_direction = [
2420 2
                'RTL' => [1, 13, 14, 15, 21],
2421
                'LTR' => [0, 11, 12, 20],
2422
            ];
2423
2424 2
            if (\in_array($tmp_return, $char_direction['LTR'], true)) {
2425
                return 'LTR';
2426
            }
2427
2428 2
            if (\in_array($tmp_return, $char_direction['RTL'], true)) {
2429 2
                return 'RTL';
2430
            }
2431
        }
2432
2433 2
        $c = static::chr_to_decimal($char);
2434
2435 2
        if (!($c >= 0x5be && $c <= 0x10b7f)) {
2436 2
            return 'LTR';
2437
        }
2438
2439 2
        if ($c <= 0x85e) {
2440 2
            if ($c === 0x5be ||
2441 2
                $c === 0x5c0 ||
2442 2
                $c === 0x5c3 ||
2443 2
                $c === 0x5c6 ||
2444 2
                ($c >= 0x5d0 && $c <= 0x5ea) ||
2445 2
                ($c >= 0x5f0 && $c <= 0x5f4) ||
2446 2
                $c === 0x608 ||
2447 2
                $c === 0x60b ||
2448 2
                $c === 0x60d ||
2449 2
                $c === 0x61b ||
2450 2
                ($c >= 0x61e && $c <= 0x64a) ||
2451
                ($c >= 0x66d && $c <= 0x66f) ||
2452
                ($c >= 0x671 && $c <= 0x6d5) ||
2453
                ($c >= 0x6e5 && $c <= 0x6e6) ||
2454
                ($c >= 0x6ee && $c <= 0x6ef) ||
2455
                ($c >= 0x6fa && $c <= 0x70d) ||
2456
                $c === 0x710 ||
2457
                ($c >= 0x712 && $c <= 0x72f) ||
2458
                ($c >= 0x74d && $c <= 0x7a5) ||
2459
                $c === 0x7b1 ||
2460
                ($c >= 0x7c0 && $c <= 0x7ea) ||
2461
                ($c >= 0x7f4 && $c <= 0x7f5) ||
2462
                $c === 0x7fa ||
2463
                ($c >= 0x800 && $c <= 0x815) ||
2464
                $c === 0x81a ||
2465
                $c === 0x824 ||
2466
                $c === 0x828 ||
2467
                ($c >= 0x830 && $c <= 0x83e) ||
2468
                ($c >= 0x840 && $c <= 0x858) ||
2469 2
                $c === 0x85e
2470
            ) {
2471 2
                return 'RTL';
2472
            }
2473 2
        } elseif ($c === 0x200f) {
2474
            return 'RTL';
2475 2
        } elseif ($c >= 0xfb1d) {
2476 2
            if ($c === 0xfb1d ||
2477 2
                ($c >= 0xfb1f && $c <= 0xfb28) ||
2478 2
                ($c >= 0xfb2a && $c <= 0xfb36) ||
2479 2
                ($c >= 0xfb38 && $c <= 0xfb3c) ||
2480 2
                $c === 0xfb3e ||
2481 2
                ($c >= 0xfb40 && $c <= 0xfb41) ||
2482 2
                ($c >= 0xfb43 && $c <= 0xfb44) ||
2483 2
                ($c >= 0xfb46 && $c <= 0xfbc1) ||
2484 2
                ($c >= 0xfbd3 && $c <= 0xfd3d) ||
2485 2
                ($c >= 0xfd50 && $c <= 0xfd8f) ||
2486 2
                ($c >= 0xfd92 && $c <= 0xfdc7) ||
2487 2
                ($c >= 0xfdf0 && $c <= 0xfdfc) ||
2488 2
                ($c >= 0xfe70 && $c <= 0xfe74) ||
2489 2
                ($c >= 0xfe76 && $c <= 0xfefc) ||
2490 2
                ($c >= 0x10800 && $c <= 0x10805) ||
2491 2
                $c === 0x10808 ||
2492 2
                ($c >= 0x1080a && $c <= 0x10835) ||
2493 2
                ($c >= 0x10837 && $c <= 0x10838) ||
2494 2
                $c === 0x1083c ||
2495 2
                ($c >= 0x1083f && $c <= 0x10855) ||
2496 2
                ($c >= 0x10857 && $c <= 0x1085f) ||
2497 2
                ($c >= 0x10900 && $c <= 0x1091b) ||
2498 2
                ($c >= 0x10920 && $c <= 0x10939) ||
2499 2
                $c === 0x1093f ||
2500 2
                $c === 0x10a00 ||
2501 2
                ($c >= 0x10a10 && $c <= 0x10a13) ||
2502 2
                ($c >= 0x10a15 && $c <= 0x10a17) ||
2503 2
                ($c >= 0x10a19 && $c <= 0x10a33) ||
2504 2
                ($c >= 0x10a40 && $c <= 0x10a47) ||
2505 2
                ($c >= 0x10a50 && $c <= 0x10a58) ||
2506 2
                ($c >= 0x10a60 && $c <= 0x10a7f) ||
2507 2
                ($c >= 0x10b00 && $c <= 0x10b35) ||
2508 2
                ($c >= 0x10b40 && $c <= 0x10b55) ||
2509 2
                ($c >= 0x10b58 && $c <= 0x10b72) ||
2510 2
                ($c >= 0x10b78 && $c <= 0x10b7f)
2511
            ) {
2512 2
                return 'RTL';
2513
            }
2514
        }
2515
2516 2
        return 'LTR';
2517
    }
2518
2519
    /**
2520
     * Check for php-support.
2521
     *
2522
     * @param string|null $key
2523
     *
2524
     * @psalm-pure
2525
     *
2526
     * @return mixed
2527
     *               Return the full support-"array", if $key === null<br>
2528
     *               return bool-value, if $key is used and available<br>
2529
     *               otherwise return <strong>null</strong>
2530
     */
2531 27
    public static function getSupportInfo(string $key = null)
2532
    {
2533 27
        if ($key === null) {
2534 4
            return self::$SUPPORT;
2535
        }
2536
2537 25
        if (self::$INTL_TRANSLITERATOR_LIST === null) {
2538 1
            self::$INTL_TRANSLITERATOR_LIST = self::getData('transliterator_list');
2539
        }
2540
        // compatibility fix for old versions
2541 25
        self::$SUPPORT['intl__transliterator_list_ids'] = self::$INTL_TRANSLITERATOR_LIST;
2542
2543 25
        return self::$SUPPORT[$key] ?? null;
2544
    }
2545
2546
    /**
2547
     * Warning: this method only works for some file-types (png, jpg)
2548
     *          if you need more supported types, please use e.g. "finfo"
2549
     *
2550
     * @param string $str
2551
     * @param array  $fallback <p>with this keys: 'ext', 'mime', 'type'
2552
     *
2553
     * @psalm-pure
2554
     *
2555
     * @return null[]|string[]
2556
     *                         <p>with this keys: 'ext', 'mime', 'type'</p>
2557
     *
2558
     * @phpstan-param array{ext: null|string, mime: null|string, type: null|string} $fallback
2559
     */
2560 40
    public static function get_file_type(
2561
        string $str,
2562
        array $fallback = [
2563
            'ext'  => null,
2564
            'mime' => 'application/octet-stream',
2565
            'type' => null,
2566
        ]
2567
    ): array {
2568 40
        if ($str === '') {
2569
            return $fallback;
2570
        }
2571
2572
        /** @var false|string $str_info - needed for PhpStan (stubs error) */
2573 40
        $str_info = \substr($str, 0, 2);
2574 40
        if ($str_info === false || \strlen($str_info) !== 2) {
2575 11
            return $fallback;
2576
        }
2577
2578
        // DEBUG
2579
        //var_dump($str_info);
2580
2581 36
        $str_info = \unpack('C2chars', $str_info);
2582
2583
        /** @noinspection PhpSillyAssignmentInspection */
2584
        /** @var array|false $str_info - needed for PhpStan (stubs error) */
2585 36
        $str_info = $str_info;
2586
2587 36
        if ($str_info === false) {
2588
            return $fallback;
2589
        }
2590
        /** @noinspection OffsetOperationsInspection */
2591 36
        $type_code = (int) ($str_info['chars1'] . $str_info['chars2']);
2592
2593
        // DEBUG
2594
        //var_dump($type_code);
2595
2596
        //
2597
        // info: https://en.wikipedia.org/wiki/Magic_number_%28programming%29#Format_indicator
2598
        //
2599
        switch ($type_code) {
2600
            // WARNING: do not add too simple comparisons, because of false-positive results:
2601
            //
2602
            // 3780 => 'pdf', 7790 => 'exe', 7784 => 'midi', 8075 => 'zip',
2603
            // 8297 => 'rar', 7173 => 'gif', 7373 => 'tiff' 6677 => 'bmp', ...
2604
            //
2605 36
            case 255216:
2606
                $ext = 'jpg';
2607
                $mime = 'image/jpeg';
2608
                $type = 'binary';
2609
2610
                break;
2611 36
            case 13780:
2612 7
                $ext = 'png';
2613 7
                $mime = 'image/png';
2614 7
                $type = 'binary';
2615
2616 7
                break;
2617
            default:
2618 35
                return $fallback;
2619
        }
2620
2621
        return [
2622 7
            'ext'  => $ext,
2623 7
            'mime' => $mime,
2624 7
            'type' => $type,
2625
        ];
2626
    }
2627
2628
    /**
2629
     * @param int    $length         <p>Length of the random string.</p>
2630
     * @param string $possible_chars [optional] <p>Characters string for the random selection.</p>
2631
     * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
2632
     *
2633
     * @return string
2634
     */
2635 1
    public static function get_random_string(
2636
        int $length,
2637
        string $possible_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
2638
        string $encoding = 'UTF-8'
2639
    ): string {
2640
        // init
2641 1
        $i = 0;
2642 1
        $str = '';
2643
2644
        //
2645
        // add random chars
2646
        //
2647
2648 1
        if ($encoding === 'UTF-8') {
2649 1
            $max_length = (int) \mb_strlen($possible_chars);
2650 1
            if ($max_length === 0) {
2651 1
                return '';
2652
            }
2653
2654 1
            while ($i < $length) {
2655
                try {
2656 1
                    $rand_int = \random_int(0, $max_length - 1);
2657
                } catch (\Exception $e) {
2658
                    /** @noinspection RandomApiMigrationInspection */
2659
                    $rand_int = \mt_rand(0, $max_length - 1);
2660
                }
2661 1
                $char = \mb_substr($possible_chars, $rand_int, 1);
2662 1
                if ($char !== false) {
2663 1
                    $str .= $char;
2664 1
                    ++$i;
2665
                }
2666
            }
2667
        } else {
2668
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
2669
2670
            $max_length = (int) self::strlen($possible_chars, $encoding);
2671
            if ($max_length === 0) {
2672
                return '';
2673
            }
2674
2675
            while ($i < $length) {
2676
                try {
2677
                    $rand_int = \random_int(0, $max_length - 1);
2678
                } catch (\Exception $e) {
2679
                    /** @noinspection RandomApiMigrationInspection */
2680
                    $rand_int = \mt_rand(0, $max_length - 1);
2681
                }
2682
                $char = self::substr($possible_chars, $rand_int, 1, $encoding);
2683
                if ($char !== false) {
2684
                    $str .= $char;
2685
                    ++$i;
2686
                }
2687
            }
2688
        }
2689
2690 1
        return $str;
2691
    }
2692
2693
    /**
2694
     * @param int|string $extra_entropy [optional] <p>Extra entropy via a string or int value.</p>
2695
     * @param bool       $use_md5       [optional] <p>Return the unique identifier as md5-hash? Default: true</p>
2696
     *
2697
     * @return string
2698
     */
2699 1
    public static function get_unique_string($extra_entropy = '', bool $use_md5 = true): string
2700
    {
2701
        try {
2702 1
            $rand_int = \random_int(0, \mt_getrandmax());
2703
        } catch (\Exception $e) {
2704
            /** @noinspection RandomApiMigrationInspection */
2705
            $rand_int = \mt_rand(0, \mt_getrandmax());
2706
        }
2707
2708
        $unique_helper = $rand_int .
2709 1
                         \session_id() .
2710 1
                         ($_SERVER['REMOTE_ADDR'] ?? '') .
2711 1
                         ($_SERVER['SERVER_ADDR'] ?? '') .
2712 1
                         $extra_entropy;
2713
2714 1
        $unique_string = \uniqid($unique_helper, true);
2715
2716 1
        if ($use_md5) {
2717 1
            $unique_string = \md5($unique_string . $unique_helper);
2718
        }
2719
2720 1
        return $unique_string;
2721
    }
2722
2723
    /**
2724
     * alias for "UTF8::string_has_bom()"
2725
     *
2726
     * @param string $str
2727
     *
2728
     * @psalm-pure
2729
     *
2730
     * @return bool
2731
     *
2732
     * @see        UTF8::string_has_bom()
2733
     * @deprecated <p>please use "UTF8::string_has_bom()"</p>
2734
     */
2735 2
    public static function hasBom(string $str): bool
2736
    {
2737 2
        return self::string_has_bom($str);
2738
    }
2739
2740
    /**
2741
     * Returns true if the string contains a lower case char, false otherwise.
2742
     *
2743
     * @param string $str <p>The input string.</p>
2744
     *
2745
     * @psalm-pure
2746
     *
2747
     * @return bool
2748
     *              <p>Whether or not the string contains a lower case character.</p>
2749
     */
2750 47
    public static function has_lowercase(string $str): bool
2751
    {
2752 47
        if (self::$SUPPORT['mbstring'] === true) {
2753
            /** @noinspection PhpComposerExtensionStubsInspection */
2754 47
            return \mb_ereg_match('.*[[:lower:]]', $str);
2755
        }
2756
2757
        return self::str_matches_pattern($str, '.*[[:lower:]]');
2758
    }
2759
2760
    /**
2761
     * Returns true if the string contains whitespace, false otherwise.
2762
     *
2763
     * @param string $str <p>The input string.</p>
2764
     *
2765
     * @psalm-pure
2766
     *
2767
     * @return bool
2768
     *              <p>Whether or not the string contains whitespace.</p>
2769
     */
2770 11
    public static function has_whitespace(string $str): bool
2771
    {
2772 11
        if (self::$SUPPORT['mbstring'] === true) {
2773
            /** @noinspection PhpComposerExtensionStubsInspection */
2774 11
            return \mb_ereg_match('.*[[:space:]]', $str);
2775
        }
2776
2777
        return self::str_matches_pattern($str, '.*[[:space:]]');
2778
    }
2779
2780
    /**
2781
     * Returns true if the string contains an upper case char, false otherwise.
2782
     *
2783
     * @param string $str <p>The input string.</p>
2784
     *
2785
     * @psalm-pure
2786
     *
2787
     * @return bool
2788
     *              <p>Whether or not the string contains an upper case character.</p>
2789
     */
2790 12
    public static function has_uppercase(string $str): bool
2791
    {
2792 12
        if (self::$SUPPORT['mbstring'] === true) {
2793
            /** @noinspection PhpComposerExtensionStubsInspection */
2794 12
            return \mb_ereg_match('.*[[:upper:]]', $str);
2795
        }
2796
2797
        return self::str_matches_pattern($str, '.*[[:upper:]]');
2798
    }
2799
2800
    /**
2801
     * Converts a hexadecimal value into a UTF-8 character.
2802
     *
2803
     * INFO: opposite to UTF8::chr_to_hex()
2804
     *
2805
     * EXAMPLE: <code>UTF8::hex_to_chr('U+00a7'); // '§'</code>
2806
     *
2807
     * @param string $hexdec <p>The hexadecimal value.</p>
2808
     *
2809
     * @psalm-pure
2810
     *
2811
     * @return false|string one single UTF-8 character
2812
     */
2813 4
    public static function hex_to_chr(string $hexdec)
2814
    {
2815
        /** @noinspection PhpUsageOfSilenceOperatorInspection - Invalid characters passed for attempted conversion, these have been ignored */
2816 4
        return self::decimal_to_chr((int) @\hexdec($hexdec));
2817
    }
2818
2819
    /**
2820
     * Converts hexadecimal U+xxxx code point representation to integer.
2821
     *
2822
     * INFO: opposite to UTF8::int_to_hex()
2823
     *
2824
     * EXAMPLE: <code>UTF8::hex_to_int('U+00f1'); // 241</code>
2825
     *
2826
     * @param string $hexdec <p>The hexadecimal code point representation.</p>
2827
     *
2828
     * @psalm-pure
2829
     *
2830
     * @return false|int
2831
     *                   <p>The code point, or false on failure.</p>
2832
     */
2833 2
    public static function hex_to_int($hexdec)
2834
    {
2835
        // init
2836 2
        $hexdec = (string) $hexdec;
2837
2838 2
        if ($hexdec === '') {
2839 2
            return false;
2840
        }
2841
2842 2
        if (\preg_match('/^(?:\\\u|U\+|)([a-zA-Z0-9]{4,6})$/', $hexdec, $match)) {
2843 2
            return \intval($match[1], 16);
2844
        }
2845
2846 2
        return false;
2847
    }
2848
2849
    /**
2850
     * alias for "UTF8::html_entity_decode()"
2851
     *
2852
     * @param string   $str
2853
     * @param int|null $flags
2854
     * @param string   $encoding
2855
     *
2856
     * @psalm-pure
2857
     *
2858
     * @return string
2859
     *
2860
     * @see        UTF8::html_entity_decode()
2861
     * @deprecated <p>please use "UTF8::html_entity_decode()"</p>
2862
     */
2863 2
    public static function html_decode(
2864
        string $str,
2865
        int $flags = null,
2866
        string $encoding = 'UTF-8'
2867
    ): string {
2868 2
        return self::html_entity_decode($str, $flags, $encoding);
2869
    }
2870
2871
    /**
2872
     * Converts a UTF-8 string to a series of HTML numbered entities.
2873
     *
2874
     * INFO: opposite to UTF8::html_decode()
2875
     *
2876
     * EXAMPLE: <code>UTF8::html_encode('中文空白'); // '&#20013;&#25991;&#31354;&#30333;'</code>
2877
     *
2878
     * @param string $str              <p>The Unicode string to be encoded as numbered entities.</p>
2879
     * @param bool   $keep_ascii_chars [optional] <p>Keep ASCII chars.</p>
2880
     * @param string $encoding         [optional] <p>Set the charset for e.g. "mb_" function</p>
2881
     *
2882
     * @psalm-pure
2883
     *
2884
     * @return string HTML numbered entities
2885
     */
2886 14
    public static function html_encode(
2887
        string $str,
2888
        bool $keep_ascii_chars = false,
2889
        string $encoding = 'UTF-8'
2890
    ): string {
2891 14
        if ($str === '') {
2892 4
            return '';
2893
        }
2894
2895 14
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2896 4
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
2897
        }
2898
2899
        // INFO: http://stackoverflow.com/questions/35854535/better-explanation-of-convmap-in-mb-encode-numericentity
2900 14
        if (self::$SUPPORT['mbstring'] === true) {
2901 14
            if ($keep_ascii_chars) {
2902 13
                $start_code = 0x80;
2903
            } else {
2904 3
                $start_code = 0x00;
2905
            }
2906
2907 14
            if ($encoding === 'UTF-8') {
2908
                /** @var false|string|null $return - needed for PhpStan (stubs error) */
2909 14
                $return = \mb_encode_numericentity(
2910 14
                    $str,
2911 14
                    [$start_code, 0xfffff, 0, 0xfffff]
2912
                );
2913 14
                if ($return !== null && $return !== false) {
2914 14
                    return $return;
2915
                }
2916
            }
2917
2918
            /** @var false|string|null $return - needed for PhpStan (stubs error) */
2919 4
            $return = \mb_encode_numericentity(
2920 4
                $str,
2921 4
                [$start_code, 0xfffff, 0, 0xfffff],
2922 4
                $encoding
2923
            );
2924 4
            if ($return !== null && $return !== false) {
2925 4
                return $return;
2926
            }
2927
        }
2928
2929
        //
2930
        // fallback via vanilla php
2931
        //
2932
2933
        return \implode(
2934
            '',
2935
            \array_map(
2936
                static function (string $chr) use ($keep_ascii_chars, $encoding): string {
2937
                    return self::single_chr_html_encode($chr, $keep_ascii_chars, $encoding);
2938
                },
2939
                self::str_split($str)
2940
            )
2941
        );
2942
    }
2943
2944
    /**
2945
     * UTF-8 version of html_entity_decode()
2946
     *
2947
     * The reason we are not using html_entity_decode() by itself is because
2948
     * while it is not technically correct to leave out the semicolon
2949
     * at the end of an entity most browsers will still interpret the entity
2950
     * correctly. html_entity_decode() does not convert entities without
2951
     * semicolons, so we are left with our own little solution here. Bummer.
2952
     *
2953
     * Convert all HTML entities to their applicable characters.
2954
     *
2955
     * INFO: opposite to UTF8::html_encode()
2956
     *
2957
     * EXAMPLE: <code>UTF8::html_entity_decode('&#20013;&#25991;&#31354;&#30333;'); // '中文空白'</code>
2958
     *
2959
     * @see http://php.net/manual/en/function.html-entity-decode.php
2960
     *
2961
     * @param string   $str      <p>
2962
     *                           The input string.
2963
     *                           </p>
2964
     * @param int|null $flags    [optional] <p>
2965
     *                           A bitmask of one or more of the following flags, which specify how to handle quotes
2966
     *                           and which document type to use. The default is ENT_COMPAT | ENT_HTML401.
2967
     *                           <table>
2968
     *                           Available <i>flags</i> constants
2969
     *                           <tr valign="top">
2970
     *                           <td>Constant Name</td>
2971
     *                           <td>Description</td>
2972
     *                           </tr>
2973
     *                           <tr valign="top">
2974
     *                           <td><b>ENT_COMPAT</b></td>
2975
     *                           <td>Will convert double-quotes and leave single-quotes alone.</td>
2976
     *                           </tr>
2977
     *                           <tr valign="top">
2978
     *                           <td><b>ENT_QUOTES</b></td>
2979
     *                           <td>Will convert both double and single quotes.</td>
2980
     *                           </tr>
2981
     *                           <tr valign="top">
2982
     *                           <td><b>ENT_NOQUOTES</b></td>
2983
     *                           <td>Will leave both double and single quotes unconverted.</td>
2984
     *                           </tr>
2985
     *                           <tr valign="top">
2986
     *                           <td><b>ENT_HTML401</b></td>
2987
     *                           <td>
2988
     *                           Handle code as HTML 4.01.
2989
     *                           </td>
2990
     *                           </tr>
2991
     *                           <tr valign="top">
2992
     *                           <td><b>ENT_XML1</b></td>
2993
     *                           <td>
2994
     *                           Handle code as XML 1.
2995
     *                           </td>
2996
     *                           </tr>
2997
     *                           <tr valign="top">
2998
     *                           <td><b>ENT_XHTML</b></td>
2999
     *                           <td>
3000
     *                           Handle code as XHTML.
3001
     *                           </td>
3002
     *                           </tr>
3003
     *                           <tr valign="top">
3004
     *                           <td><b>ENT_HTML5</b></td>
3005
     *                           <td>
3006
     *                           Handle code as HTML 5.
3007
     *                           </td>
3008
     *                           </tr>
3009
     *                           </table>
3010
     *                           </p>
3011
     * @param string   $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
3012
     *
3013
     * @psalm-pure
3014
     *
3015
     * @return string the decoded string
3016
     */
3017 51
    public static function html_entity_decode(
3018
        string $str,
3019
        int $flags = null,
3020
        string $encoding = 'UTF-8'
3021
    ): string {
3022
        if (
3023 51
            !isset($str[3]) // examples: &; || &x;
3024
            ||
3025 51
            \strpos($str, '&') === false // no "&"
3026
        ) {
3027 24
            return $str;
3028
        }
3029
3030 49
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
3031 9
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
3032
        }
3033
3034 49
        if ($flags === null) {
3035 11
            $flags = \ENT_QUOTES | \ENT_HTML5;
3036
        }
3037
3038
        /** @noinspection InArrayCanBeUsedInspection */
3039
        if (
3040 49
            $encoding !== 'UTF-8'
3041
            &&
3042 49
            $encoding !== 'ISO-8859-1'
3043
            &&
3044 49
            $encoding !== 'WINDOWS-1252'
3045
            &&
3046 49
            self::$SUPPORT['mbstring'] === false
3047
        ) {
3048
            /**
3049
             * @psalm-suppress ImpureFunctionCall - is is only a warning
3050
             */
3051
            \trigger_error('UTF8::html_entity_decode() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
3052
        }
3053
3054
        do {
3055 49
            $str_compare = $str;
3056
3057 49
            if (\strpos($str, '&') !== false) {
3058 49
                if (\strpos($str, '&#') !== false) {
3059
                    // decode also numeric & UTF16 two byte entities
3060 41
                    $str = (string) \preg_replace(
3061 41
                        '/(&#(?:x0*[0-9a-fA-F]{2,6}(?![0-9a-fA-F;])|(?:0*\d{2,6}(?![0-9;]))))/S',
3062 41
                        '$1;',
3063 41
                        $str
3064
                    );
3065
                }
3066
3067 49
                $str = \html_entity_decode(
3068 49
                    $str,
3069 49
                    $flags,
3070 49
                    $encoding
3071
                );
3072
            }
3073 49
        } while ($str_compare !== $str);
3074
3075 49
        return $str;
3076
    }
3077
3078
    /**
3079
     * Create a escape html version of the string via "UTF8::htmlspecialchars()".
3080
     *
3081
     * @param string $str
3082
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
3083
     *
3084
     * @psalm-pure
3085
     *
3086
     * @return string
3087
     */
3088 6
    public static function html_escape(string $str, string $encoding = 'UTF-8'): string
3089
    {
3090 6
        return self::htmlspecialchars(
3091 6
            $str,
3092 6
            \ENT_QUOTES | \ENT_SUBSTITUTE,
3093 6
            $encoding
3094
        );
3095
    }
3096
3097
    /**
3098
     * Remove empty html-tag.
3099
     *
3100
     * e.g.: <pre><tag></tag></pre>
3101
     *
3102
     * @param string $str
3103
     *
3104
     * @psalm-pure
3105
     *
3106
     * @return string
3107
     */
3108 1
    public static function html_stripe_empty_tags(string $str): string
3109
    {
3110 1
        return (string) \preg_replace(
3111 1
            '/<[^\\/>]*?>\\s*?<\\/[^>]*?>/u',
3112 1
            '',
3113 1
            $str
3114
        );
3115
    }
3116
3117
    /**
3118
     * Convert all applicable characters to HTML entities: UTF-8 version of htmlentities().
3119
     *
3120
     * EXAMPLE: <code>UTF8::htmlentities('<白-öäü>'); // '&lt;&#30333;-&ouml;&auml;&uuml;&gt;'</code>
3121
     *
3122
     * @see http://php.net/manual/en/function.htmlentities.php
3123
     *
3124
     * @param string $str           <p>
3125
     *                              The input string.
3126
     *                              </p>
3127
     * @param int    $flags         [optional] <p>
3128
     *                              A bitmask of one or more of the following flags, which specify how to handle
3129
     *                              quotes, invalid code unit sequences and the used document type. The default is
3130
     *                              ENT_COMPAT | ENT_HTML401.
3131
     *                              <table>
3132
     *                              Available <i>flags</i> constants
3133
     *                              <tr valign="top">
3134
     *                              <td>Constant Name</td>
3135
     *                              <td>Description</td>
3136
     *                              </tr>
3137
     *                              <tr valign="top">
3138
     *                              <td><b>ENT_COMPAT</b></td>
3139
     *                              <td>Will convert double-quotes and leave single-quotes alone.</td>
3140
     *                              </tr>
3141
     *                              <tr valign="top">
3142
     *                              <td><b>ENT_QUOTES</b></td>
3143
     *                              <td>Will convert both double and single quotes.</td>
3144
     *                              </tr>
3145
     *                              <tr valign="top">
3146
     *                              <td><b>ENT_NOQUOTES</b></td>
3147
     *                              <td>Will leave both double and single quotes unconverted.</td>
3148
     *                              </tr>
3149
     *                              <tr valign="top">
3150
     *                              <td><b>ENT_IGNORE</b></td>
3151
     *                              <td>
3152
     *                              Silently discard invalid code unit sequences instead of returning
3153
     *                              an empty string. Using this flag is discouraged as it
3154
     *                              may have security implications.
3155
     *                              </td>
3156
     *                              </tr>
3157
     *                              <tr valign="top">
3158
     *                              <td><b>ENT_SUBSTITUTE</b></td>
3159
     *                              <td>
3160
     *                              Replace invalid code unit sequences with a Unicode Replacement Character
3161
     *                              U+FFFD (UTF-8) or &#38;#38;#FFFD; (otherwise) instead of returning an empty
3162
     *                              string.
3163
     *                              </td>
3164
     *                              </tr>
3165
     *                              <tr valign="top">
3166
     *                              <td><b>ENT_DISALLOWED</b></td>
3167
     *                              <td>
3168
     *                              Replace invalid code points for the given document type with a
3169
     *                              Unicode Replacement Character U+FFFD (UTF-8) or &#38;#38;#FFFD;
3170
     *                              (otherwise) instead of leaving them as is. This may be useful, for
3171
     *                              instance, to ensure the well-formedness of XML documents with
3172
     *                              embedded external content.
3173
     *                              </td>
3174
     *                              </tr>
3175
     *                              <tr valign="top">
3176
     *                              <td><b>ENT_HTML401</b></td>
3177
     *                              <td>
3178
     *                              Handle code as HTML 4.01.
3179
     *                              </td>
3180
     *                              </tr>
3181
     *                              <tr valign="top">
3182
     *                              <td><b>ENT_XML1</b></td>
3183
     *                              <td>
3184
     *                              Handle code as XML 1.
3185
     *                              </td>
3186
     *                              </tr>
3187
     *                              <tr valign="top">
3188
     *                              <td><b>ENT_XHTML</b></td>
3189
     *                              <td>
3190
     *                              Handle code as XHTML.
3191
     *                              </td>
3192
     *                              </tr>
3193
     *                              <tr valign="top">
3194
     *                              <td><b>ENT_HTML5</b></td>
3195
     *                              <td>
3196
     *                              Handle code as HTML 5.
3197
     *                              </td>
3198
     *                              </tr>
3199
     *                              </table>
3200
     *                              </p>
3201
     * @param string $encoding      [optional] <p>
3202
     *                              Like <b>htmlspecialchars</b>,
3203
     *                              <b>htmlentities</b> takes an optional third argument
3204
     *                              <i>encoding</i> which defines encoding used in
3205
     *                              conversion.
3206
     *                              Although this argument is technically optional, you are highly
3207
     *                              encouraged to specify the correct value for your code.
3208
     *                              </p>
3209
     * @param bool   $double_encode [optional] <p>
3210
     *                              When <i>double_encode</i> is turned off PHP will not
3211
     *                              encode existing html entities. The default is to convert everything.
3212
     *                              </p>
3213
     *
3214
     * @psalm-pure
3215
     *
3216
     * @return string
3217
     *                <p>
3218
     *                The encoded string.
3219
     *                <br><br>
3220
     *                If the input <i>string</i> contains an invalid code unit
3221
     *                sequence within the given <i>encoding</i> an empty string
3222
     *                will be returned, unless either the <b>ENT_IGNORE</b> or
3223
     *                <b>ENT_SUBSTITUTE</b> flags are set.
3224
     *                </p>
3225
     */
3226 9
    public static function htmlentities(
3227
        string $str,
3228
        int $flags = \ENT_COMPAT,
3229
        string $encoding = 'UTF-8',
3230
        bool $double_encode = true
3231
    ): string {
3232 9
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
3233 7
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
3234
        }
3235
3236 9
        $str = \htmlentities(
3237 9
            $str,
3238 9
            $flags,
3239 9
            $encoding,
3240 9
            $double_encode
3241
        );
3242
3243
        /**
3244
         * PHP doesn't replace a backslash to its html entity since this is something
3245
         * that's mostly used to escape characters when inserting in a database. Since
3246
         * we're using a decent database layer, we don't need this shit and we're replacing
3247
         * the double backslashes by its' html entity equivalent.
3248
         *
3249
         * https://github.com/forkcms/library/blob/master/spoon/filter/filter.php#L303
3250
         */
3251 9
        $str = \str_replace('\\', '&#92;', $str);
3252
3253 9
        return self::html_encode($str, true, $encoding);
3254
    }
3255
3256
    /**
3257
     * Convert only special characters to HTML entities: UTF-8 version of htmlspecialchars()
3258
     *
3259
     * INFO: Take a look at "UTF8::htmlentities()"
3260
     *
3261
     * EXAMPLE: <code>UTF8::htmlspecialchars('<白-öäü>'); // '&lt;白-öäü&gt;'</code>
3262
     *
3263
     * @see http://php.net/manual/en/function.htmlspecialchars.php
3264
     *
3265
     * @param string $str           <p>
3266
     *                              The string being converted.
3267
     *                              </p>
3268
     * @param int    $flags         [optional] <p>
3269
     *                              A bitmask of one or more of the following flags, which specify how to handle
3270
     *                              quotes, invalid code unit sequences and the used document type. The default is
3271
     *                              ENT_COMPAT | ENT_HTML401.
3272
     *                              <table>
3273
     *                              Available <i>flags</i> constants
3274
     *                              <tr valign="top">
3275
     *                              <td>Constant Name</td>
3276
     *                              <td>Description</td>
3277
     *                              </tr>
3278
     *                              <tr valign="top">
3279
     *                              <td><b>ENT_COMPAT</b></td>
3280
     *                              <td>Will convert double-quotes and leave single-quotes alone.</td>
3281
     *                              </tr>
3282
     *                              <tr valign="top">
3283
     *                              <td><b>ENT_QUOTES</b></td>
3284
     *                              <td>Will convert both double and single quotes.</td>
3285
     *                              </tr>
3286
     *                              <tr valign="top">
3287
     *                              <td><b>ENT_NOQUOTES</b></td>
3288
     *                              <td>Will leave both double and single quotes unconverted.</td>
3289
     *                              </tr>
3290
     *                              <tr valign="top">
3291
     *                              <td><b>ENT_IGNORE</b></td>
3292
     *                              <td>
3293
     *                              Silently discard invalid code unit sequences instead of returning
3294
     *                              an empty string. Using this flag is discouraged as it
3295
     *                              may have security implications.
3296
     *                              </td>
3297
     *                              </tr>
3298
     *                              <tr valign="top">
3299
     *                              <td><b>ENT_SUBSTITUTE</b></td>
3300
     *                              <td>
3301
     *                              Replace invalid code unit sequences with a Unicode Replacement Character
3302
     *                              U+FFFD (UTF-8) or &#38;#38;#FFFD; (otherwise) instead of returning an empty
3303
     *                              string.
3304
     *                              </td>
3305
     *                              </tr>
3306
     *                              <tr valign="top">
3307
     *                              <td><b>ENT_DISALLOWED</b></td>
3308
     *                              <td>
3309
     *                              Replace invalid code points for the given document type with a
3310
     *                              Unicode Replacement Character U+FFFD (UTF-8) or &#38;#38;#FFFD;
3311
     *                              (otherwise) instead of leaving them as is. This may be useful, for
3312
     *                              instance, to ensure the well-formedness of XML documents with
3313
     *                              embedded external content.
3314
     *                              </td>
3315
     *                              </tr>
3316
     *                              <tr valign="top">
3317
     *                              <td><b>ENT_HTML401</b></td>
3318
     *                              <td>
3319
     *                              Handle code as HTML 4.01.
3320
     *                              </td>
3321
     *                              </tr>
3322
     *                              <tr valign="top">
3323
     *                              <td><b>ENT_XML1</b></td>
3324
     *                              <td>
3325
     *                              Handle code as XML 1.
3326
     *                              </td>
3327
     *                              </tr>
3328
     *                              <tr valign="top">
3329
     *                              <td><b>ENT_XHTML</b></td>
3330
     *                              <td>
3331
     *                              Handle code as XHTML.
3332
     *                              </td>
3333
     *                              </tr>
3334
     *                              <tr valign="top">
3335
     *                              <td><b>ENT_HTML5</b></td>
3336
     *                              <td>
3337
     *                              Handle code as HTML 5.
3338
     *                              </td>
3339
     *                              </tr>
3340
     *                              </table>
3341
     *                              </p>
3342
     * @param string $encoding      [optional] <p>
3343
     *                              Defines encoding used in conversion.
3344
     *                              </p>
3345
     *                              <p>
3346
     *                              For the purposes of this function, the encodings
3347
     *                              ISO-8859-1, ISO-8859-15,
3348
     *                              UTF-8, cp866,
3349
     *                              cp1251, cp1252, and
3350
     *                              KOI8-R are effectively equivalent, provided the
3351
     *                              <i>string</i> itself is valid for the encoding, as
3352
     *                              the characters affected by <b>htmlspecialchars</b> occupy
3353
     *                              the same positions in all of these encodings.
3354
     *                              </p>
3355
     * @param bool   $double_encode [optional] <p>
3356
     *                              When <i>double_encode</i> is turned off PHP will not
3357
     *                              encode existing html entities, the default is to convert everything.
3358
     *                              </p>
3359
     *
3360
     * @psalm-pure
3361
     *
3362
     * @return string the converted string.
3363
     *                </p>
3364
     *                <p>
3365
     *                If the input <i>string</i> contains an invalid code unit
3366
     *                sequence within the given <i>encoding</i> an empty string
3367
     *                will be returned, unless either the <b>ENT_IGNORE</b> or
3368
     *                <b>ENT_SUBSTITUTE</b> flags are set
3369
     */
3370 8
    public static function htmlspecialchars(
3371
        string $str,
3372
        int $flags = \ENT_COMPAT,
3373
        string $encoding = 'UTF-8',
3374
        bool $double_encode = true
3375
    ): string {
3376 8
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
3377 8
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
3378
        }
3379
3380 8
        return \htmlspecialchars(
3381 8
            $str,
3382 8
            $flags,
3383 8
            $encoding,
3384 8
            $double_encode
3385
        );
3386
    }
3387
3388
    /**
3389
     * Checks whether iconv is available on the server.
3390
     *
3391
     * @psalm-pure
3392
     *
3393
     * @return bool
3394
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
3395
     *
3396
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
3397
     */
3398
    public static function iconv_loaded(): bool
3399
    {
3400
        return \extension_loaded('iconv');
3401
    }
3402
3403
    /**
3404
     * alias for "UTF8::decimal_to_chr()"
3405
     *
3406
     * @param int|string $int
3407
     *
3408
     * @phpstan-param int|numeric-string $int
3409
     *
3410
     * @psalm-pure
3411
     *
3412
     * @return string
3413
     *
3414
     * @see        UTF8::decimal_to_chr()
3415
     * @deprecated <p>please use "UTF8::decimal_to_chr()"</p>
3416
     */
3417 4
    public static function int_to_chr($int): string
3418
    {
3419 4
        return self::decimal_to_chr($int);
3420
    }
3421
3422
    /**
3423
     * Converts Integer to hexadecimal U+xxxx code point representation.
3424
     *
3425
     * INFO: opposite to UTF8::hex_to_int()
3426
     *
3427
     * EXAMPLE: <code>UTF8::int_to_hex(241); // 'U+00f1'</code>
3428
     *
3429
     * @param int    $int    <p>The integer to be converted to hexadecimal code point.</p>
3430
     * @param string $prefix [optional]
3431
     *
3432
     * @psalm-pure
3433
     *
3434
     * @return string the code point, or empty string on failure
3435
     */
3436 6
    public static function int_to_hex(int $int, string $prefix = 'U+'): string
3437
    {
3438 6
        $hex = \dechex($int);
3439
3440 6
        $hex = (\strlen($hex) < 4 ? \substr('0000' . $hex, -4) : $hex);
3441
3442 6
        return $prefix . $hex . '';
3443
    }
3444
3445
    /**
3446
     * Checks whether intl-char is available on the server.
3447
     *
3448
     * @psalm-pure
3449
     *
3450
     * @return bool
3451
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
3452
     *
3453
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
3454
     */
3455
    public static function intlChar_loaded(): bool
3456
    {
3457
        return \class_exists('IntlChar');
3458
    }
3459
3460
    /**
3461
     * Checks whether intl is available on the server.
3462
     *
3463
     * @psalm-pure
3464
     *
3465
     * @return bool
3466
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
3467
     *
3468
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
3469
     */
3470 5
    public static function intl_loaded(): bool
3471
    {
3472 5
        return \extension_loaded('intl');
3473
    }
3474
3475
    /**
3476
     * alias for "UTF8::is_ascii()"
3477
     *
3478
     * @param string $str
3479
     *
3480
     * @psalm-pure
3481
     *
3482
     * @return bool
3483
     *
3484
     * @see        UTF8::is_ascii()
3485
     * @deprecated <p>please use "UTF8::is_ascii()"</p>
3486
     */
3487 2
    public static function isAscii(string $str): bool
3488
    {
3489 2
        return ASCII::is_ascii($str);
3490
    }
3491
3492
    /**
3493
     * alias for "UTF8::is_base64()"
3494
     *
3495
     * @param string $str
3496
     *
3497
     * @psalm-pure
3498
     *
3499
     * @return bool
3500
     *
3501
     * @see        UTF8::is_base64()
3502
     * @deprecated <p>please use "UTF8::is_base64()"</p>
3503
     */
3504 2
    public static function isBase64($str): bool
3505
    {
3506 2
        return self::is_base64($str);
3507
    }
3508
3509
    /**
3510
     * alias for "UTF8::is_binary()"
3511
     *
3512
     * @param int|string $str
3513
     * @param bool       $strict
3514
     *
3515
     * @psalm-pure
3516
     *
3517
     * @return bool
3518
     *
3519
     * @see        UTF8::is_binary()
3520
     * @deprecated <p>please use "UTF8::is_binary()"</p>
3521
     */
3522 4
    public static function isBinary($str, bool $strict = false): bool
3523
    {
3524 4
        return self::is_binary($str, $strict);
3525
    }
3526
3527
    /**
3528
     * alias for "UTF8::is_bom()"
3529
     *
3530
     * @param string $utf8_chr
3531
     *
3532
     * @psalm-pure
3533
     *
3534
     * @return bool
3535
     *
3536
     * @see        UTF8::is_bom()
3537
     * @deprecated <p>please use "UTF8::is_bom()"</p>
3538
     */
3539 2
    public static function isBom(string $utf8_chr): bool
3540
    {
3541 2
        return self::is_bom($utf8_chr);
3542
    }
3543
3544
    /**
3545
     * alias for "UTF8::is_html()"
3546
     *
3547
     * @param string $str
3548
     *
3549
     * @psalm-pure
3550
     *
3551
     * @return bool
3552
     *
3553
     * @see        UTF8::is_html()
3554
     * @deprecated <p>please use "UTF8::is_html()"</p>
3555
     */
3556 2
    public static function isHtml(string $str): bool
3557
    {
3558 2
        return self::is_html($str);
3559
    }
3560
3561
    /**
3562
     * alias for "UTF8::is_json()"
3563
     *
3564
     * @param string $str
3565
     *
3566
     * @return bool
3567
     *
3568
     * @see        UTF8::is_json()
3569
     * @deprecated <p>please use "UTF8::is_json()"</p>
3570
     */
3571 1
    public static function isJson(string $str): bool
3572
    {
3573 1
        return self::is_json($str);
3574
    }
3575
3576
    /**
3577
     * alias for "UTF8::is_utf16()"
3578
     *
3579
     * @param string $str
3580
     *
3581
     * @psalm-pure
3582
     *
3583
     * @return false|int
3584
     *                   <strong>false</strong> if is't not UTF16,<br>
3585
     *                   <strong>1</strong> for UTF-16LE,<br>
3586
     *                   <strong>2</strong> for UTF-16BE
3587
     *
3588
     * @see        UTF8::is_utf16()
3589
     * @deprecated <p>please use "UTF8::is_utf16()"</p>
3590
     */
3591 2
    public static function isUtf16($str)
3592
    {
3593 2
        return self::is_utf16($str);
3594
    }
3595
3596
    /**
3597
     * alias for "UTF8::is_utf32()"
3598
     *
3599
     * @param string $str
3600
     *
3601
     * @psalm-pure
3602
     *
3603
     * @return false|int
3604
     *                   <strong>false</strong> if is't not UTF16,
3605
     *                   <strong>1</strong> for UTF-32LE,
3606
     *                   <strong>2</strong> for UTF-32BE
3607
     *
3608
     * @see        UTF8::is_utf32()
3609
     * @deprecated <p>please use "UTF8::is_utf32()"</p>
3610
     */
3611 2
    public static function isUtf32($str)
3612
    {
3613 2
        return self::is_utf32($str);
3614
    }
3615
3616
    /**
3617
     * alias for "UTF8::is_utf8()"
3618
     *
3619
     * @param string $str
3620
     * @param bool   $strict
3621
     *
3622
     * @psalm-pure
3623
     *
3624
     * @return bool
3625
     *
3626
     * @see        UTF8::is_utf8()
3627
     * @deprecated <p>please use "UTF8::is_utf8()"</p>
3628
     */
3629 17
    public static function isUtf8($str, bool $strict = false): bool
3630
    {
3631 17
        return self::is_utf8($str, $strict);
3632
    }
3633
3634
    /**
3635
     * Returns true if the string contains only alphabetic chars, false otherwise.
3636
     *
3637
     * @param string $str <p>The input string.</p>
3638
     *
3639
     * @psalm-pure
3640
     *
3641
     * @return bool
3642
     *              <p>Whether or not $str contains only alphabetic chars.</p>
3643
     */
3644 10
    public static function is_alpha(string $str): bool
3645
    {
3646 10
        if (self::$SUPPORT['mbstring'] === true) {
3647
            /** @noinspection PhpComposerExtensionStubsInspection */
3648 10
            return \mb_ereg_match('^[[:alpha:]]*$', $str);
3649
        }
3650
3651
        return self::str_matches_pattern($str, '^[[:alpha:]]*$');
3652
    }
3653
3654
    /**
3655
     * Returns true if the string contains only alphabetic and numeric chars, false otherwise.
3656
     *
3657
     * @param string $str <p>The input string.</p>
3658
     *
3659
     * @psalm-pure
3660
     *
3661
     * @return bool
3662
     *              <p>Whether or not $str contains only alphanumeric chars.</p>
3663
     */
3664 13
    public static function is_alphanumeric(string $str): bool
3665
    {
3666 13
        if (self::$SUPPORT['mbstring'] === true) {
3667
            /** @noinspection PhpComposerExtensionStubsInspection */
3668 13
            return \mb_ereg_match('^[[:alnum:]]*$', $str);
3669
        }
3670
3671
        return self::str_matches_pattern($str, '^[[:alnum:]]*$');
3672
    }
3673
3674
    /**
3675
     * Returns true if the string contains only punctuation chars, false otherwise.
3676
     *
3677
     * @param string $str <p>The input string.</p>
3678
     *
3679
     * @psalm-pure
3680
     *
3681
     * @return bool
3682
     *              <p>Whether or not $str contains only punctuation chars.</p>
3683
     */
3684 10
    public static function is_punctuation(string $str): bool
3685
    {
3686 10
        return self::str_matches_pattern($str, '^[[:punct:]]*$');
3687
    }
3688
3689
    /**
3690
     * Returns true if the string contains only printable (non-invisible) chars, false otherwise.
3691
     *
3692
     * @param string $str <p>The input string.</p>
3693
     *
3694
     * @psalm-pure
3695
     *
3696
     * @return bool
3697
     *              <p>Whether or not $str contains only printable (non-invisible) chars.</p>
3698
     */
3699 1
    public static function is_printable(string $str): bool
3700
    {
3701 1
        return self::remove_invisible_characters($str) === $str;
3702
    }
3703
3704
    /**
3705
     * Checks if a string is 7 bit ASCII.
3706
     *
3707
     * EXAMPLE: <code>UTF8::is_ascii('白'); // false</code>
3708
     *
3709
     * @param string $str <p>The string to check.</p>
3710
     *
3711
     * @psalm-pure
3712
     *
3713
     * @return bool
3714
     *              <p>
3715
     *              <strong>true</strong> if it is ASCII<br>
3716
     *              <strong>false</strong> otherwise
3717
     *              </p>
3718
     */
3719 8
    public static function is_ascii(string $str): bool
3720
    {
3721 8
        return ASCII::is_ascii($str);
3722
    }
3723
3724
    /**
3725
     * Returns true if the string is base64 encoded, false otherwise.
3726
     *
3727
     * EXAMPLE: <code>UTF8::is_base64('4KSu4KWL4KSo4KS/4KSa'); // true</code>
3728
     *
3729
     * @param string|null $str                   <p>The input string.</p>
3730
     * @param bool        $empty_string_is_valid [optional] <p>Is an empty string valid base64 or not?</p>
3731
     *
3732
     * @psalm-pure
3733
     *
3734
     * @return bool
3735
     *              <p>Whether or not $str is base64 encoded.</p>
3736
     */
3737 16
    public static function is_base64($str, bool $empty_string_is_valid = false): bool
3738
    {
3739
        if (
3740 16
            !$empty_string_is_valid
3741
            &&
3742 16
            $str === ''
3743
        ) {
3744 3
            return false;
3745
        }
3746
3747 15
        if (!\is_string($str)) {
3748 2
            return false;
3749
        }
3750
3751 15
        $base64String = \base64_decode($str, true);
3752
3753 15
        return $base64String !== false && \base64_encode($base64String) === $str;
3754
    }
3755
3756
    /**
3757
     * Check if the input is binary... (is look like a hack).
3758
     *
3759
     * EXAMPLE: <code>UTF8::is_binary(01); // true</code>
3760
     *
3761
     * @param int|string $input
3762
     * @param bool       $strict
3763
     *
3764
     * @psalm-pure
3765
     *
3766
     * @return bool
3767
     */
3768 40
    public static function is_binary($input, bool $strict = false): bool
3769
    {
3770 40
        $input = (string) $input;
3771 40
        if ($input === '') {
3772 10
            return false;
3773
        }
3774
3775 40
        if (\preg_match('~^[01]+$~', $input)) {
3776 13
            return true;
3777
        }
3778
3779 40
        $ext = self::get_file_type($input);
3780 40
        if ($ext['type'] === 'binary') {
3781 7
            return true;
3782
        }
3783
3784 39
        $test_length = \strlen($input);
3785 39
        $test_null_counting = \substr_count($input, "\x0", 0, $test_length);
3786 39
        if (($test_null_counting / $test_length) > 0.25) {
3787 15
            return true;
3788
        }
3789
3790 35
        if ($strict) {
3791 35
            if (self::$SUPPORT['finfo'] === false) {
3792
                throw new \RuntimeException('ext-fileinfo: is not installed');
3793
            }
3794
3795
            /**
3796
             * @noinspection   PhpComposerExtensionStubsInspection
3797
             * @psalm-suppress ImpureMethodCall - it will return the same result for the same file ...
3798
             */
3799 35
            $finfo_encoding = (new \finfo(\FILEINFO_MIME_ENCODING))->buffer($input);
3800 35
            if ($finfo_encoding && $finfo_encoding === 'binary') {
3801 15
                return true;
3802
            }
3803
        }
3804
3805 31
        return false;
3806
    }
3807
3808
    /**
3809
     * Check if the file is binary.
3810
     *
3811
     * EXAMPLE: <code>UTF8::is_binary('./utf32.txt'); // true</code>
3812
     *
3813
     * @param string $file
3814
     *
3815
     * @return bool
3816
     */
3817 6
    public static function is_binary_file($file): bool
3818
    {
3819
        // init
3820 6
        $block = '';
3821
3822 6
        $fp = \fopen($file, 'rb');
3823 6
        if (\is_resource($fp)) {
3824 6
            $block = \fread($fp, 512);
3825 6
            \fclose($fp);
3826
        }
3827
3828 6
        if ($block === '' || $block === false) {
3829 2
            return false;
3830
        }
3831
3832 6
        return self::is_binary($block, true);
3833
    }
3834
3835
    /**
3836
     * Returns true if the string contains only whitespace chars, false otherwise.
3837
     *
3838
     * @param string $str <p>The input string.</p>
3839
     *
3840
     * @psalm-pure
3841
     *
3842
     * @return bool
3843
     *              <p>Whether or not $str contains only whitespace characters.</p>
3844
     */
3845 15
    public static function is_blank(string $str): bool
3846
    {
3847 15
        if (self::$SUPPORT['mbstring'] === true) {
3848
            /** @noinspection PhpComposerExtensionStubsInspection */
3849 15
            return \mb_ereg_match('^[[:space:]]*$', $str);
3850
        }
3851
3852
        return self::str_matches_pattern($str, '^[[:space:]]*$');
3853
    }
3854
3855
    /**
3856
     * Checks if the given string is equal to any "Byte Order Mark".
3857
     *
3858
     * WARNING: Use "UTF8::string_has_bom()" if you will check BOM in a string.
3859
     *
3860
     * EXAMPLE: <code>UTF8::is_bom("\xef\xbb\xbf"); // true</code>
3861
     *
3862
     * @param string $str <p>The input string.</p>
3863
     *
3864
     * @psalm-pure
3865
     *
3866
     * @return bool
3867
     *              <p><strong>true</strong> if the $utf8_chr is Byte Order Mark, <strong>false</strong> otherwise.</p>
3868
     */
3869 2
    public static function is_bom($str): bool
3870
    {
3871
        /** @noinspection PhpUnusedLocalVariableInspection */
3872 2
        foreach (self::$BOM as $bom_string => &$bom_byte_length) {
3873 2
            if ($str === $bom_string) {
3874 2
                return true;
3875
            }
3876
        }
3877
3878 2
        return false;
3879
    }
3880
3881
    /**
3882
     * Determine whether the string is considered to be empty.
3883
     *
3884
     * A variable is considered empty if it does not exist or if its value equals FALSE.
3885
     * empty() does not generate a warning if the variable does not exist.
3886
     *
3887
     * @param array|float|int|string $str
3888
     *
3889
     * @psalm-pure
3890
     *
3891
     * @return bool
3892
     *              <p>Whether or not $str is empty().</p>
3893
     */
3894 1
    public static function is_empty($str): bool
3895
    {
3896 1
        return empty($str);
3897
    }
3898
3899
    /**
3900
     * Returns true if the string contains only hexadecimal chars, false otherwise.
3901
     *
3902
     * @param string $str <p>The input string.</p>
3903
     *
3904
     * @psalm-pure
3905
     *
3906
     * @return bool
3907
     *              <p>Whether or not $str contains only hexadecimal chars.</p>
3908
     */
3909 13
    public static function is_hexadecimal(string $str): bool
3910
    {
3911 13
        if (self::$SUPPORT['mbstring'] === true) {
3912
            /** @noinspection PhpComposerExtensionStubsInspection */
3913 13
            return \mb_ereg_match('^[[:xdigit:]]*$', $str);
3914
        }
3915
3916
        return self::str_matches_pattern($str, '^[[:xdigit:]]*$');
3917
    }
3918
3919
    /**
3920
     * Check if the string contains any HTML tags.
3921
     *
3922
     * EXAMPLE: <code>UTF8::is_html('<b>lall</b>'); // true</code>
3923
     *
3924
     * @param string $str <p>The input string.</p>
3925
     *
3926
     * @psalm-pure
3927
     *
3928
     * @return bool
3929
     *              <p>Whether or not $str contains html elements.</p>
3930
     */
3931 3
    public static function is_html(string $str): bool
3932
    {
3933 3
        if ($str === '') {
3934 3
            return false;
3935
        }
3936
3937
        // init
3938 3
        $matches = [];
3939
3940 3
        $str = self::emoji_encode($str); // hack for emoji support :/
3941
3942 3
        \preg_match("/<\\/?\\w+(?:(?:\\s+\\w+(?:\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)*\\s*|\\s*)\\/?>/u", $str, $matches);
3943
3944 3
        return $matches !== [];
3945
    }
3946
3947
    /**
3948
     * Check if $url is an correct url.
3949
     *
3950
     * @param string $url
3951
     * @param bool   $disallow_localhost
3952
     *
3953
     * @psalm-pure
3954
     *
3955
     * @return bool
3956
     */
3957 1
    public static function is_url(string $url, bool $disallow_localhost = false): bool
3958
    {
3959 1
        if ($url === '') {
3960 1
            return false;
3961
        }
3962
3963
        // WARNING: keep this as hack protection
3964 1
        if (!self::str_istarts_with_any($url, ['http://', 'https://'])) {
3965 1
            return false;
3966
        }
3967
3968
        // e.g. -> the server itself connect to "https://foo.localhost/phpmyadmin/...
3969 1
        if ($disallow_localhost) {
3970 1
            if (self::str_istarts_with_any(
3971 1
                $url,
3972
                [
3973 1
                    'http://localhost',
3974
                    'https://localhost',
3975
                    'http://127.0.0.1',
3976
                    'https://127.0.0.1',
3977
                    'http://::1',
3978
                    'https://::1',
3979
                ]
3980
            )) {
3981 1
                return false;
3982
            }
3983
3984 1
            $regex = '/^(?:http(?:s)?:\/\/).*?(?:\.localhost)/iu';
3985
            /** @noinspection BypassedUrlValidationInspection */
3986 1
            if (\preg_match($regex, $url)) {
3987 1
                return false;
3988
            }
3989
        }
3990
3991
        // INFO: this is needed for e.g. "http://müller.de/" (internationalized domain names) and non ASCII-parameters
3992
        /** @noinspection SuspiciousAssignmentsInspection - false-positive - https://github.com/kalessil/phpinspectionsea/issues/1500 */
3993 1
        $regex = '/^(?:http(?:s)?:\\/\\/)(?:[\p{L}0-9][\p{L}0-9_-]*(?:\\.[\p{L}0-9][\p{L}0-9_-]*))(?:\\d+)?(?:\\/\\.*)?/iu';
3994
        /** @noinspection BypassedUrlValidationInspection */
3995 1
        if (\preg_match($regex, $url)) {
3996 1
            return true;
3997
        }
3998
3999
        /** @noinspection BypassedUrlValidationInspection */
4000 1
        return \filter_var($url, \FILTER_VALIDATE_URL) !== false;
4001
    }
4002
4003
    /**
4004
     * Try to check if "$str" is a JSON-string.
4005
     *
4006
     * EXAMPLE: <code>UTF8::is_json('{"array":[1,"¥","ä"]}'); // true</code>
4007
     *
4008
     * @param string $str                                    <p>The input string.</p>
4009
     * @param bool   $only_array_or_object_results_are_valid [optional] <p>Only array and objects are valid json
4010
     *                                                       results.</p>
4011
     *
4012
     * @return bool
4013
     *              <p>Whether or not the $str is in JSON format.</p>
4014
     */
4015 42
    public static function is_json(string $str, bool $only_array_or_object_results_are_valid = true): bool
4016
    {
4017 42
        if ($str === '') {
4018 4
            return false;
4019
        }
4020
4021 40
        if (self::$SUPPORT['json'] === false) {
4022
            throw new \RuntimeException('ext-json: is not installed');
4023
        }
4024
4025 40
        $jsonOrNull = self::json_decode($str);
4026 40
        if ($jsonOrNull === null && \strtoupper($str) !== 'NULL') {
4027 18
            return false;
4028
        }
4029
4030
        if (
4031 24
            $only_array_or_object_results_are_valid
4032
            &&
4033 24
            !\is_object($jsonOrNull)
4034
            &&
4035 24
            !\is_array($jsonOrNull)
4036
        ) {
4037 5
            return false;
4038
        }
4039
4040
        /** @noinspection PhpComposerExtensionStubsInspection */
4041 19
        return \json_last_error() === \JSON_ERROR_NONE;
4042
    }
4043
4044
    /**
4045
     * @param string $str <p>The input string.</p>
4046
     *
4047
     * @psalm-pure
4048
     *
4049
     * @return bool
4050
     *              <p>Whether or not $str contains only lowercase chars.</p>
4051
     */
4052 8
    public static function is_lowercase(string $str): bool
4053
    {
4054 8
        if (self::$SUPPORT['mbstring'] === true) {
4055
            /** @noinspection PhpComposerExtensionStubsInspection */
4056 8
            return \mb_ereg_match('^[[:lower:]]*$', $str);
4057
        }
4058
4059
        return self::str_matches_pattern($str, '^[[:lower:]]*$');
4060
    }
4061
4062
    /**
4063
     * Returns true if the string is serialized, false otherwise.
4064
     *
4065
     * @param string $str <p>The input string.</p>
4066
     *
4067
     * @psalm-pure
4068
     *
4069
     * @return bool
4070
     *              <p>Whether or not $str is serialized.</p>
4071
     */
4072 7
    public static function is_serialized(string $str): bool
4073
    {
4074 7
        if ($str === '') {
4075 1
            return false;
4076
        }
4077
4078
        /** @noinspection PhpUsageOfSilenceOperatorInspection */
4079
        /** @noinspection UnserializeExploitsInspection */
4080 6
        return $str === 'b:0;'
4081
               ||
4082 6
               @\unserialize($str) !== false;
4083
    }
4084
4085
    /**
4086
     * Returns true if the string contains only lower case chars, false
4087
     * otherwise.
4088
     *
4089
     * @param string $str <p>The input string.</p>
4090
     *
4091
     * @psalm-pure
4092
     *
4093
     * @return bool
4094
     *              <p>Whether or not $str contains only lower case characters.</p>
4095
     */
4096 8
    public static function is_uppercase(string $str): bool
4097
    {
4098 8
        if (self::$SUPPORT['mbstring'] === true) {
4099
            /** @noinspection PhpComposerExtensionStubsInspection */
4100 8
            return \mb_ereg_match('^[[:upper:]]*$', $str);
4101
        }
4102
4103
        return self::str_matches_pattern($str, '^[[:upper:]]*$');
4104
    }
4105
4106
    /**
4107
     * Check if the string is UTF-16.
4108
     *
4109
     * EXAMPLE: <code>
4110
     * UTF8::is_utf16(file_get_contents('utf-16-le.txt')); // 1
4111
     * //
4112
     * UTF8::is_utf16(file_get_contents('utf-16-be.txt')); // 2
4113
     * //
4114
     * UTF8::is_utf16(file_get_contents('utf-8.txt')); // false
4115
     * </code>
4116
     *
4117
     * @param string $str                       <p>The input string.</p>
4118
     * @param bool   $check_if_string_is_binary
4119
     *
4120
     * @psalm-pure
4121
     *
4122
     * @return false|int
4123
     *                   <strong>false</strong> if is't not UTF-16,<br>
4124
     *                   <strong>1</strong> for UTF-16LE,<br>
4125
     *                   <strong>2</strong> for UTF-16BE
4126
     */
4127 22
    public static function is_utf16($str, bool $check_if_string_is_binary = true)
4128
    {
4129
        // init
4130 22
        $str = (string) $str;
4131 22
        $str_chars = [];
4132
4133
        if (
4134 22
            $check_if_string_is_binary
4135
            &&
4136 22
            !self::is_binary($str, true)
4137
        ) {
4138 2
            return false;
4139
        }
4140
4141 22
        if (self::$SUPPORT['mbstring'] === false) {
4142
            /**
4143
             * @psalm-suppress ImpureFunctionCall - is is only a warning
4144
             */
4145 3
            \trigger_error('UTF8::is_utf16() without mbstring may did not work correctly', \E_USER_WARNING);
4146
        }
4147
4148 22
        $str = self::remove_bom($str);
4149
4150 22
        $maybe_utf16le = 0;
4151 22
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-16LE');
4152 22
        if ($test) {
4153 15
            $test2 = \mb_convert_encoding($test, 'UTF-16LE', 'UTF-8');
4154 15
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-16LE');
4155 15
            if ($test3 === $test) {
4156
                /**
4157
                 * @psalm-suppress RedundantCondition
4158
                 */
4159 15
                if ($str_chars === []) {
4160 15
                    $str_chars = self::count_chars($str, true, false);
4161
                }
4162 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...
4163 15
                    if (\in_array($test3char, $str_chars, true)) {
4164 15
                        ++$maybe_utf16le;
4165
                    }
4166
                }
4167 15
                unset($test3charEmpty);
4168
            }
4169
        }
4170
4171 22
        $maybe_utf16be = 0;
4172 22
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-16BE');
4173 22
        if ($test) {
4174 15
            $test2 = \mb_convert_encoding($test, 'UTF-16BE', 'UTF-8');
4175 15
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-16BE');
4176 15
            if ($test3 === $test) {
4177 15
                if ($str_chars === []) {
4178 7
                    $str_chars = self::count_chars($str, true, false);
4179
                }
4180 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...
4181 15
                    if (\in_array($test3char, $str_chars, true)) {
4182 15
                        ++$maybe_utf16be;
4183
                    }
4184
                }
4185 15
                unset($test3charEmpty);
4186
            }
4187
        }
4188
4189 22
        if ($maybe_utf16be !== $maybe_utf16le) {
4190 7
            if ($maybe_utf16le > $maybe_utf16be) {
4191 5
                return 1;
4192
            }
4193
4194 6
            return 2;
4195
        }
4196
4197 18
        return false;
4198
    }
4199
4200
    /**
4201
     * Check if the string is UTF-32.
4202
     *
4203
     * EXAMPLE: <code>
4204
     * UTF8::is_utf32(file_get_contents('utf-32-le.txt')); // 1
4205
     * //
4206
     * UTF8::is_utf32(file_get_contents('utf-32-be.txt')); // 2
4207
     * //
4208
     * UTF8::is_utf32(file_get_contents('utf-8.txt')); // false
4209
     * </code>
4210
     *
4211
     * @param string $str                       <p>The input string.</p>
4212
     * @param bool   $check_if_string_is_binary
4213
     *
4214
     * @psalm-pure
4215
     *
4216
     * @return false|int
4217
     *                   <strong>false</strong> if is't not UTF-32,<br>
4218
     *                   <strong>1</strong> for UTF-32LE,<br>
4219
     *                   <strong>2</strong> for UTF-32BE
4220
     */
4221 20
    public static function is_utf32($str, bool $check_if_string_is_binary = true)
4222
    {
4223
        // init
4224 20
        $str = (string) $str;
4225 20
        $str_chars = [];
4226
4227
        if (
4228 20
            $check_if_string_is_binary
4229
            &&
4230 20
            !self::is_binary($str, true)
4231
        ) {
4232 2
            return false;
4233
        }
4234
4235 20
        if (self::$SUPPORT['mbstring'] === false) {
4236
            /**
4237
             * @psalm-suppress ImpureFunctionCall - is is only a warning
4238
             */
4239 3
            \trigger_error('UTF8::is_utf32() without mbstring may did not work correctly', \E_USER_WARNING);
4240
        }
4241
4242 20
        $str = self::remove_bom($str);
4243
4244 20
        $maybe_utf32le = 0;
4245 20
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-32LE');
4246 20
        if ($test) {
4247 13
            $test2 = \mb_convert_encoding($test, 'UTF-32LE', 'UTF-8');
4248 13
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-32LE');
4249 13
            if ($test3 === $test) {
4250
                /**
4251
                 * @psalm-suppress RedundantCondition
4252
                 */
4253 13
                if ($str_chars === []) {
4254 13
                    $str_chars = self::count_chars($str, true, false);
4255
                }
4256 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...
4257 13
                    if (\in_array($test3char, $str_chars, true)) {
4258 13
                        ++$maybe_utf32le;
4259
                    }
4260
                }
4261 13
                unset($test3charEmpty);
4262
            }
4263
        }
4264
4265 20
        $maybe_utf32be = 0;
4266 20
        $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-32BE');
4267 20
        if ($test) {
4268 13
            $test2 = \mb_convert_encoding($test, 'UTF-32BE', 'UTF-8');
4269 13
            $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-32BE');
4270 13
            if ($test3 === $test) {
4271 13
                if ($str_chars === []) {
4272 7
                    $str_chars = self::count_chars($str, true, false);
4273
                }
4274 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...
4275 13
                    if (\in_array($test3char, $str_chars, true)) {
4276 13
                        ++$maybe_utf32be;
4277
                    }
4278
                }
4279 13
                unset($test3charEmpty);
4280
            }
4281
        }
4282
4283 20
        if ($maybe_utf32be !== $maybe_utf32le) {
4284 3
            if ($maybe_utf32le > $maybe_utf32be) {
4285 2
                return 1;
4286
            }
4287
4288 3
            return 2;
4289
        }
4290
4291 20
        return false;
4292
    }
4293
4294
    /**
4295
     * Checks whether the passed input contains only byte sequences that appear valid UTF-8.
4296
     *
4297
     * EXAMPLE: <code>
4298
     * UTF8::is_utf8(['Iñtërnâtiônàlizætiøn', 'foo']); // true
4299
     * //
4300
     * UTF8::is_utf8(["Iñtërnâtiônàlizætiøn\xA0\xA1", 'bar']); // false
4301
     * </code>
4302
     *
4303
     * @param int|string|string[]|null $str    <p>The input to be checked.</p>
4304
     * @param bool                     $strict <p>Check also if the string is not UTF-16 or UTF-32.</p>
4305
     *
4306
     * @psalm-pure
4307
     *
4308
     * @return bool
4309
     */
4310 83
    public static function is_utf8($str, bool $strict = false): bool
4311
    {
4312 83
        if (\is_array($str)) {
4313 2
            foreach ($str as &$v) {
4314 2
                if (!self::is_utf8($v, $strict)) {
4315 2
                    return false;
4316
                }
4317
            }
4318
4319
            return true;
4320
        }
4321
4322 83
        return self::is_utf8_string((string) $str, $strict);
4323
    }
4324
4325
    /**
4326
     * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
4327
     * Decodes a JSON string
4328
     *
4329
     * EXAMPLE: <code>UTF8::json_decode('[1,"\u00a5","\u00e4"]'); // array(1, '¥', 'ä')</code>
4330
     *
4331
     * @see http://php.net/manual/en/function.json-decode.php
4332
     *
4333
     * @param string $json    <p>
4334
     *                        The <i>json</i> string being decoded.
4335
     *                        </p>
4336
     *                        <p>
4337
     *                        This function only works with UTF-8 encoded strings.
4338
     *                        </p>
4339
     *                        <p>PHP implements a superset of
4340
     *                        JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
4341
     *                        only supports these values when they are nested inside an array or an object.
4342
     *                        </p>
4343
     * @param bool   $assoc   [optional] <p>
4344
     *                        When <b>TRUE</b>, returned objects will be converted into
4345
     *                        associative arrays.
4346
     *                        </p>
4347
     * @param int    $depth   [optional] <p>
4348
     *                        User specified recursion depth.
4349
     *                        </p>
4350
     * @param int    $options [optional] <p>
4351
     *                        Bitmask of JSON decode options. Currently only
4352
     *                        <b>JSON_BIGINT_AS_STRING</b>
4353
     *                        is supported (default is to cast large integers as floats)
4354
     *                        </p>
4355
     *
4356
     * @psalm-pure
4357
     *
4358
     * @return mixed
4359
     *               <p>The value encoded in <i>json</i> in appropriate PHP type. Values true, false and
4360
     *               null (case-insensitive) are returned as <b>TRUE</b>, <b>FALSE</b> and <b>NULL</b> respectively.
4361
     *               <b>NULL</b> is returned if the <i>json</i> cannot be decoded or if the encoded data
4362
     *               is deeper than the recursion limit.</p>
4363
     */
4364 43
    public static function json_decode(
4365
        string $json,
4366
        bool $assoc = false,
4367
        int $depth = 512,
4368
        int $options = 0
4369
    ) {
4370 43
        $json = self::filter($json);
4371
4372 43
        if (self::$SUPPORT['json'] === false) {
4373
            throw new \RuntimeException('ext-json: is not installed');
4374
        }
4375
4376
        /** @noinspection PhpComposerExtensionStubsInspection */
4377 43
        return \json_decode($json, $assoc, $depth, $options);
4378
    }
4379
4380
    /**
4381
     * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
4382
     * Returns the JSON representation of a value.
4383
     *
4384
     * EXAMPLE: <code>UTF8::json_enocde(array(1, '¥', 'ä')); // '[1,"\u00a5","\u00e4"]'</code>
4385
     *
4386
     * @see http://php.net/manual/en/function.json-encode.php
4387
     *
4388
     * @param mixed $value   <p>
4389
     *                       The <i>value</i> being encoded. Can be any type except
4390
     *                       a resource.
4391
     *                       </p>
4392
     *                       <p>
4393
     *                       All string data must be UTF-8 encoded.
4394
     *                       </p>
4395
     *                       <p>PHP implements a superset of
4396
     *                       JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
4397
     *                       only supports these values when they are nested inside an array or an object.
4398
     *                       </p>
4399
     * @param int   $options [optional] <p>
4400
     *                       Bitmask consisting of <b>JSON_HEX_QUOT</b>,
4401
     *                       <b>JSON_HEX_TAG</b>,
4402
     *                       <b>JSON_HEX_AMP</b>,
4403
     *                       <b>JSON_HEX_APOS</b>,
4404
     *                       <b>JSON_NUMERIC_CHECK</b>,
4405
     *                       <b>JSON_PRETTY_PRINT</b>,
4406
     *                       <b>JSON_UNESCAPED_SLASHES</b>,
4407
     *                       <b>JSON_FORCE_OBJECT</b>,
4408
     *                       <b>JSON_UNESCAPED_UNICODE</b>. The behaviour of these
4409
     *                       constants is described on
4410
     *                       the JSON constants page.
4411
     *                       </p>
4412
     * @param int   $depth   [optional] <p>
4413
     *                       Set the maximum depth. Must be greater than zero.
4414
     *                       </p>
4415
     *
4416
     * @psalm-pure
4417
     *
4418
     * @return false|string
4419
     *                      A JSON encoded <strong>string</strong> on success or<br>
4420
     *                      <strong>FALSE</strong> on failure
4421
     */
4422 5
    public static function json_encode($value, int $options = 0, int $depth = 512)
4423
    {
4424 5
        $value = self::filter($value);
4425
4426 5
        if (self::$SUPPORT['json'] === false) {
4427
            throw new \RuntimeException('ext-json: is not installed');
4428
        }
4429
4430
        /** @noinspection PhpComposerExtensionStubsInspection */
4431 5
        return \json_encode($value, $options, $depth);
4432
    }
4433
4434
    /**
4435
     * Checks whether JSON is available on the server.
4436
     *
4437
     * @psalm-pure
4438
     *
4439
     * @return bool
4440
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
4441
     *
4442
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
4443
     */
4444
    public static function json_loaded(): bool
4445
    {
4446
        return \function_exists('json_decode');
4447
    }
4448
4449
    /**
4450
     * Makes string's first char lowercase.
4451
     *
4452
     * EXAMPLE: <code>UTF8::lcfirst('ÑTËRNÂTIÔNÀLIZÆTIØN'); // ñTËRNÂTIÔNÀLIZÆTIØN</code>
4453
     *
4454
     * @param string      $str                           <p>The input string</p>
4455
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
4456
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
4457
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
4458
     *                                                   tr</p>
4459
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
4460
     *                                                   -> ß</p>
4461
     *
4462
     * @psalm-pure
4463
     *
4464
     * @return string the resulting string
4465
     */
4466 46
    public static function lcfirst(
4467
        string $str,
4468
        string $encoding = 'UTF-8',
4469
        bool $clean_utf8 = false,
4470
        string $lang = null,
4471
        bool $try_to_keep_the_string_length = false
4472
    ): string {
4473 46
        if ($clean_utf8) {
4474
            $str = self::clean($str);
4475
        }
4476
4477 46
        $use_mb_functions = ($lang === null && !$try_to_keep_the_string_length);
4478
4479 46
        if ($encoding === 'UTF-8') {
4480 43
            $str_part_two = (string) \mb_substr($str, 1);
4481
4482 43
            if ($use_mb_functions) {
4483 43
                $str_part_one = \mb_strtolower(
4484 43
                    (string) \mb_substr($str, 0, 1)
4485
                );
4486
            } else {
4487
                $str_part_one = self::strtolower(
4488
                    (string) \mb_substr($str, 0, 1),
4489
                    $encoding,
4490
                    false,
4491
                    $lang,
4492 43
                    $try_to_keep_the_string_length
4493
                );
4494
            }
4495
        } else {
4496 3
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
4497
4498 3
            $str_part_two = (string) self::substr($str, 1, null, $encoding);
4499
4500 3
            $str_part_one = self::strtolower(
4501 3
                (string) self::substr($str, 0, 1, $encoding),
4502 3
                $encoding,
4503 3
                false,
4504 3
                $lang,
4505 3
                $try_to_keep_the_string_length
4506
            );
4507
        }
4508
4509 46
        return $str_part_one . $str_part_two;
4510
    }
4511
4512
    /**
4513
     * alias for "UTF8::lcfirst()"
4514
     *
4515
     * @param string      $str
4516
     * @param string      $encoding
4517
     * @param bool        $clean_utf8
4518
     * @param string|null $lang
4519
     * @param bool        $try_to_keep_the_string_length
4520
     *
4521
     * @psalm-pure
4522
     *
4523
     * @return string
4524
     *
4525
     * @see        UTF8::lcfirst()
4526
     * @deprecated <p>please use "UTF8::lcfirst()"</p>
4527
     */
4528 2
    public static function lcword(
4529
        string $str,
4530
        string $encoding = 'UTF-8',
4531
        bool $clean_utf8 = false,
4532
        string $lang = null,
4533
        bool $try_to_keep_the_string_length = false
4534
    ): string {
4535 2
        return self::lcfirst(
4536 2
            $str,
4537 2
            $encoding,
4538 2
            $clean_utf8,
4539 2
            $lang,
4540 2
            $try_to_keep_the_string_length
4541
        );
4542
    }
4543
4544
    /**
4545
     * Lowercase for all words in the string.
4546
     *
4547
     * @param string      $str                           <p>The input string.</p>
4548
     * @param string[]    $exceptions                    [optional] <p>Exclusion for some words.</p>
4549
     * @param string      $char_list                     [optional] <p>Additional chars that contains to words and do
4550
     *                                                   not start a new word.</p>
4551
     * @param string      $encoding                      [optional] <p>Set the charset.</p>
4552
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
4553
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
4554
     *                                                   tr</p>
4555
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
4556
     *                                                   -> ß</p>
4557
     *
4558
     * @psalm-pure
4559
     *
4560
     * @return string
4561
     */
4562 2
    public static function lcwords(
4563
        string $str,
4564
        array $exceptions = [],
4565
        string $char_list = '',
4566
        string $encoding = 'UTF-8',
4567
        bool $clean_utf8 = false,
4568
        string $lang = null,
4569
        bool $try_to_keep_the_string_length = false
4570
    ): string {
4571 2
        if (!$str) {
4572 2
            return '';
4573
        }
4574
4575 2
        $words = self::str_to_words($str, $char_list);
4576 2
        $use_exceptions = $exceptions !== [];
4577
4578 2
        $words_str = '';
4579 2
        foreach ($words as &$word) {
4580 2
            if (!$word) {
4581 2
                continue;
4582
            }
4583
4584
            if (
4585 2
                !$use_exceptions
4586
                ||
4587 2
                !\in_array($word, $exceptions, true)
4588
            ) {
4589 2
                $words_str .= self::lcfirst($word, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
4590
            } else {
4591 2
                $words_str .= $word;
4592
            }
4593
        }
4594
4595 2
        return $words_str;
4596
    }
4597
4598
    /**
4599
     * alias for "UTF8::lcfirst()"
4600
     *
4601
     * @param string      $str
4602
     * @param string      $encoding
4603
     * @param bool        $clean_utf8
4604
     * @param string|null $lang
4605
     * @param bool        $try_to_keep_the_string_length
4606
     *
4607
     * @psalm-pure
4608
     *
4609
     * @return string
4610
     *
4611
     * @see        UTF8::lcfirst()
4612
     * @deprecated <p>please use "UTF8::lcfirst()"</p>
4613
     */
4614 5
    public static function lowerCaseFirst(
4615
        string $str,
4616
        string $encoding = 'UTF-8',
4617
        bool $clean_utf8 = false,
4618
        string $lang = null,
4619
        bool $try_to_keep_the_string_length = false
4620
    ): string {
4621 5
        return self::lcfirst(
4622 5
            $str,
4623 5
            $encoding,
4624 5
            $clean_utf8,
4625 5
            $lang,
4626 5
            $try_to_keep_the_string_length
4627
        );
4628
    }
4629
4630
    /**
4631
     * Strip whitespace or other characters from the beginning of a UTF-8 string.
4632
     *
4633
     * EXAMPLE: <code>UTF8::ltrim(' 中文空白  '); // '中文空白  '</code>
4634
     *
4635
     * @param string      $str   <p>The string to be trimmed</p>
4636
     * @param string|null $chars <p>Optional characters to be stripped</p>
4637
     *
4638
     * @psalm-pure
4639
     *
4640
     * @return string the string with unwanted characters stripped from the left
4641
     */
4642 23
    public static function ltrim(string $str = '', string $chars = null): string
4643
    {
4644 23
        if ($str === '') {
4645 3
            return '';
4646
        }
4647
4648 22
        if (self::$SUPPORT['mbstring'] === true) {
4649 22
            if ($chars !== null) {
4650
                /** @noinspection PregQuoteUsageInspection */
4651 11
                $chars = \preg_quote($chars);
4652 11
                $pattern = "^[${chars}]+";
4653
            } else {
4654 14
                $pattern = '^[\\s]+';
4655
            }
4656
4657
            /** @noinspection PhpComposerExtensionStubsInspection */
4658 22
            return (string) \mb_ereg_replace($pattern, '', $str);
4659
        }
4660
4661
        if ($chars !== null) {
4662
            $chars = \preg_quote($chars, '/');
4663
            $pattern = "^[${chars}]+";
4664
        } else {
4665
            $pattern = '^[\\s]+';
4666
        }
4667
4668
        return self::regex_replace($str, $pattern, '');
4669
    }
4670
4671
    /**
4672
     * Returns the UTF-8 character with the maximum code point in the given data.
4673
     *
4674
     * EXAMPLE: <code>UTF8::max('abc-äöü-中文空白'); // 'ø'</code>
4675
     *
4676
     * @param array<string>|string $arg <p>A UTF-8 encoded string or an array of such strings.</p>
4677
     *
4678
     * @psalm-pure
4679
     *
4680
     * @return string|null the character with the highest code point than others, returns null on failure or empty input
4681
     */
4682 2
    public static function max($arg)
4683
    {
4684 2
        if (\is_array($arg)) {
4685 2
            $arg = \implode('', $arg);
4686
        }
4687
4688 2
        $codepoints = self::codepoints($arg);
4689 2
        if ($codepoints === []) {
4690 2
            return null;
4691
        }
4692
4693 2
        $codepoint_max = \max($codepoints);
4694
4695 2
        return self::chr((int) $codepoint_max);
4696
    }
4697
4698
    /**
4699
     * Calculates and returns the maximum number of bytes taken by any
4700
     * UTF-8 encoded character in the given string.
4701
     *
4702
     * EXAMPLE: <code>UTF8::max_chr_width('Intërnâtiônàlizætiøn'); // 2</code>
4703
     *
4704
     * @param string $str <p>The original Unicode string.</p>
4705
     *
4706
     * @psalm-pure
4707
     *
4708
     * @return int
4709
     *             <p>Max byte lengths of the given chars.</p>
4710
     */
4711 2
    public static function max_chr_width(string $str): int
4712
    {
4713 2
        $bytes = self::chr_size_list($str);
4714 2
        if ($bytes !== []) {
4715 2
            return (int) \max($bytes);
4716
        }
4717
4718 2
        return 0;
4719
    }
4720
4721
    /**
4722
     * Checks whether mbstring is available on the server.
4723
     *
4724
     * @psalm-pure
4725
     *
4726
     * @return bool
4727
     *              <p><strong>true</strong> if available, <strong>false</strong> otherwise</p>
4728
     *
4729
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
4730
     */
4731 28
    public static function mbstring_loaded(): bool
4732
    {
4733 28
        return \extension_loaded('mbstring');
4734
    }
4735
4736
    /**
4737
     * Returns the UTF-8 character with the minimum code point in the given data.
4738
     *
4739
     * EXAMPLE: <code>UTF8::min('abc-äöü-中文空白'); // '-'</code>
4740
     *
4741
     * @param string|string[] $arg <strong>A UTF-8 encoded string or an array of such strings.</strong>
4742
     *
4743
     * @psalm-pure
4744
     *
4745
     * @return string|null
4746
     *                     <p>The character with the lowest code point than others, returns null on failure or empty input.</p>
4747
     */
4748 2
    public static function min($arg)
4749
    {
4750 2
        if (\is_array($arg)) {
4751 2
            $arg = \implode('', $arg);
4752
        }
4753
4754 2
        $codepoints = self::codepoints($arg);
4755 2
        if ($codepoints === []) {
4756 2
            return null;
4757
        }
4758
4759 2
        $codepoint_min = \min($codepoints);
4760
4761 2
        return self::chr((int) $codepoint_min);
4762
    }
4763
4764
    /**
4765
     * alias for "UTF8::normalize_encoding()"
4766
     *
4767
     * @param mixed $encoding
4768
     * @param mixed $fallback
4769
     *
4770
     * @psalm-pure
4771
     *
4772
     * @return mixed
4773
     *
4774
     * @see        UTF8::normalize_encoding()
4775
     * @deprecated <p>please use "UTF8::normalize_encoding()"</p>
4776
     */
4777 2
    public static function normalizeEncoding($encoding, $fallback = '')
4778
    {
4779 2
        return self::normalize_encoding($encoding, $fallback);
4780
    }
4781
4782
    /**
4783
     * Normalize the encoding-"name" input.
4784
     *
4785
     * EXAMPLE: <code>UTF8::normalize_encoding('UTF8'); // 'UTF-8'</code>
4786
     *
4787
     * @param mixed $encoding <p>e.g.: ISO, UTF8, WINDOWS-1251 etc.</p>
4788
     * @param mixed $fallback <p>e.g.: UTF-8</p>
4789
     *
4790
     * @psalm-pure
4791
     *
4792
     * @return mixed|string
4793
     *                      <p>e.g.: ISO-8859-1, UTF-8, WINDOWS-1251 etc.<br>Will return a empty string as fallback (by default)</p>
4794
     *
4795
     * @template TNormalizeEncodingFallback
4796
     * @phpstan-param string|TNormalizeEncodingFallback $fallback
4797
     * @phpstan-return string|TNormalizeEncodingFallback
4798
     */
4799 339
    public static function normalize_encoding($encoding, $fallback = '')
4800
    {
4801
        /**
4802
         * @psalm-suppress ImpureStaticVariable
4803
         *
4804
         * @var array<string,string>
4805
         */
4806 339
        static $STATIC_NORMALIZE_ENCODING_CACHE = [];
4807
4808
        // init
4809 339
        $encoding = (string) $encoding;
4810
4811 339
        if (!$encoding) {
4812 290
            return $fallback;
4813
        }
4814
4815
        if (
4816 53
            $encoding === 'UTF-8'
4817
            ||
4818 53
            $encoding === 'UTF8'
4819
        ) {
4820 29
            return 'UTF-8';
4821
        }
4822
4823
        if (
4824 44
            $encoding === '8BIT'
4825
            ||
4826 44
            $encoding === 'BINARY'
4827
        ) {
4828
            return 'CP850';
4829
        }
4830
4831
        if (
4832 44
            $encoding === 'HTML'
4833
            ||
4834 44
            $encoding === 'HTML-ENTITIES'
4835
        ) {
4836 2
            return 'HTML-ENTITIES';
4837
        }
4838
4839
        if (
4840 44
            $encoding === 'ISO'
4841
            ||
4842 44
            $encoding === 'ISO-8859-1'
4843
        ) {
4844 41
            return 'ISO-8859-1';
4845
        }
4846
4847
        if (
4848 11
            $encoding === '1' // only a fallback, for non "strict_types" usage ...
4849
            ||
4850 11
            $encoding === '0' // only a fallback, for non "strict_types" usage ...
4851
        ) {
4852
            return $fallback;
4853
        }
4854
4855 11
        if (isset($STATIC_NORMALIZE_ENCODING_CACHE[$encoding])) {
4856 8
            return $STATIC_NORMALIZE_ENCODING_CACHE[$encoding];
4857
        }
4858
4859 5
        if (self::$ENCODINGS === null) {
4860 1
            self::$ENCODINGS = self::getData('encodings');
4861
        }
4862
4863 5
        if (\in_array($encoding, self::$ENCODINGS, true)) {
4864 3
            $STATIC_NORMALIZE_ENCODING_CACHE[$encoding] = $encoding;
4865
4866 3
            return $encoding;
4867
        }
4868
4869 4
        $encoding_original = $encoding;
4870 4
        $encoding = \strtoupper($encoding);
4871 4
        $encoding_upper_helper = (string) \preg_replace('/[^a-zA-Z0-9]/u', '', $encoding);
4872
4873
        $equivalences = [
4874 4
            'ISO8859'     => 'ISO-8859-1',
4875
            'ISO88591'    => 'ISO-8859-1',
4876
            'ISO'         => 'ISO-8859-1',
4877
            'LATIN'       => 'ISO-8859-1',
4878
            'LATIN1'      => 'ISO-8859-1', // Western European
4879
            'ISO88592'    => 'ISO-8859-2',
4880
            'LATIN2'      => 'ISO-8859-2', // Central European
4881
            'ISO88593'    => 'ISO-8859-3',
4882
            'LATIN3'      => 'ISO-8859-3', // Southern European
4883
            'ISO88594'    => 'ISO-8859-4',
4884
            'LATIN4'      => 'ISO-8859-4', // Northern European
4885
            'ISO88595'    => 'ISO-8859-5',
4886
            'ISO88596'    => 'ISO-8859-6', // Greek
4887
            'ISO88597'    => 'ISO-8859-7',
4888
            'ISO88598'    => 'ISO-8859-8', // Hebrew
4889
            'ISO88599'    => 'ISO-8859-9',
4890
            'LATIN5'      => 'ISO-8859-9', // Turkish
4891
            'ISO885911'   => 'ISO-8859-11',
4892
            'TIS620'      => 'ISO-8859-11', // Thai
4893
            'ISO885910'   => 'ISO-8859-10',
4894
            'LATIN6'      => 'ISO-8859-10', // Nordic
4895
            'ISO885913'   => 'ISO-8859-13',
4896
            'LATIN7'      => 'ISO-8859-13', // Baltic
4897
            'ISO885914'   => 'ISO-8859-14',
4898
            'LATIN8'      => 'ISO-8859-14', // Celtic
4899
            'ISO885915'   => 'ISO-8859-15',
4900
            'LATIN9'      => 'ISO-8859-15', // Western European (with some extra chars e.g. €)
4901
            'ISO885916'   => 'ISO-8859-16',
4902
            'LATIN10'     => 'ISO-8859-16', // Southeast European
4903
            'CP1250'      => 'WINDOWS-1250',
4904
            'WIN1250'     => 'WINDOWS-1250',
4905
            'WINDOWS1250' => 'WINDOWS-1250',
4906
            'CP1251'      => 'WINDOWS-1251',
4907
            'WIN1251'     => 'WINDOWS-1251',
4908
            'WINDOWS1251' => 'WINDOWS-1251',
4909
            'CP1252'      => 'WINDOWS-1252',
4910
            'WIN1252'     => 'WINDOWS-1252',
4911
            'WINDOWS1252' => 'WINDOWS-1252',
4912
            'CP1253'      => 'WINDOWS-1253',
4913
            'WIN1253'     => 'WINDOWS-1253',
4914
            'WINDOWS1253' => 'WINDOWS-1253',
4915
            'CP1254'      => 'WINDOWS-1254',
4916
            'WIN1254'     => 'WINDOWS-1254',
4917
            'WINDOWS1254' => 'WINDOWS-1254',
4918
            'CP1255'      => 'WINDOWS-1255',
4919
            'WIN1255'     => 'WINDOWS-1255',
4920
            'WINDOWS1255' => 'WINDOWS-1255',
4921
            'CP1256'      => 'WINDOWS-1256',
4922
            'WIN1256'     => 'WINDOWS-1256',
4923
            'WINDOWS1256' => 'WINDOWS-1256',
4924
            'CP1257'      => 'WINDOWS-1257',
4925
            'WIN1257'     => 'WINDOWS-1257',
4926
            'WINDOWS1257' => 'WINDOWS-1257',
4927
            'CP1258'      => 'WINDOWS-1258',
4928
            'WIN1258'     => 'WINDOWS-1258',
4929
            'WINDOWS1258' => 'WINDOWS-1258',
4930
            'UTF16'       => 'UTF-16',
4931
            'UTF32'       => 'UTF-32',
4932
            'UTF8'        => 'UTF-8',
4933
            'UTF'         => 'UTF-8',
4934
            'UTF7'        => 'UTF-7',
4935
            '8BIT'        => 'CP850',
4936
            'BINARY'      => 'CP850',
4937
        ];
4938
4939 4
        if (!empty($equivalences[$encoding_upper_helper])) {
4940 3
            $encoding = $equivalences[$encoding_upper_helper];
4941
        }
4942
4943 4
        $STATIC_NORMALIZE_ENCODING_CACHE[$encoding_original] = $encoding;
4944
4945 4
        return $encoding;
4946
    }
4947
4948
    /**
4949
     * Standardize line ending to unix-like.
4950
     *
4951
     * @param string          $str      <p>The input string.</p>
4952
     * @param string|string[] $replacer <p>The replacer char e.g. "\n" (Linux) or "\r\n" (Windows). You can also use \PHP_EOL
4953
     *                                  here.</p>
4954
     *
4955
     * @psalm-pure
4956
     *
4957
     * @return string
4958
     *                <p>A string with normalized line ending.</p>
4959
     */
4960 5
    public static function normalize_line_ending(string $str, $replacer = "\n"): string
4961
    {
4962 5
        return \str_replace(["\r\n", "\r", "\n"], $replacer, $str);
4963
    }
4964
4965
    /**
4966
     * Normalize some MS Word special characters.
4967
     *
4968
     * EXAMPLE: <code>UTF8::normalize_msword('„Abcdef…”'); // '"Abcdef..."'</code>
4969
     *
4970
     * @param string $str <p>The string to be normalized.</p>
4971
     *
4972
     * @psalm-pure
4973
     *
4974
     * @return string
4975
     *                <p>A string with normalized characters for commonly used chars in Word documents.</p>
4976
     */
4977 10
    public static function normalize_msword(string $str): string
4978
    {
4979 10
        return ASCII::normalize_msword($str);
4980
    }
4981
4982
    /**
4983
     * Normalize the whitespace.
4984
     *
4985
     * EXAMPLE: <code>UTF8::normalize_whitespace("abc-\xc2\xa0-öäü-\xe2\x80\xaf-\xE2\x80\xAC", true); // "abc-\xc2\xa0-öäü- -"</code>
4986
     *
4987
     * @param string $str                        <p>The string to be normalized.</p>
4988
     * @param bool   $keep_non_breaking_space    [optional] <p>Set to true, to keep non-breaking-spaces.</p>
4989
     * @param bool   $keep_bidi_unicode_controls [optional] <p>Set to true, to keep non-printable (for the web)
4990
     *                                           bidirectional text chars.</p>
4991
     *
4992
     * @psalm-pure
4993
     *
4994
     * @return string
4995
     *                <p>A string with normalized whitespace.</p>
4996
     */
4997 61
    public static function normalize_whitespace(
4998
        string $str,
4999
        bool $keep_non_breaking_space = false,
5000
        bool $keep_bidi_unicode_controls = false
5001
    ): string {
5002 61
        return ASCII::normalize_whitespace(
5003 61
            $str,
5004 61
            $keep_non_breaking_space,
5005 61
            $keep_bidi_unicode_controls
5006
        );
5007
    }
5008
5009
    /**
5010
     * Calculates Unicode code point of the given UTF-8 encoded character.
5011
     *
5012
     * INFO: opposite to UTF8::chr()
5013
     *
5014
     * EXAMPLE: <code>UTF8::ord('☃'); // 0x2603</code>
5015
     *
5016
     * @param string $chr      <p>The character of which to calculate code point.<p/>
5017
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
5018
     *
5019
     * @psalm-pure
5020
     *
5021
     * @return int
5022
     *             <p>Unicode code point of the given character,<br>
5023
     *             0 on invalid UTF-8 byte sequence</p>
5024
     */
5025 27
    public static function ord($chr, string $encoding = 'UTF-8'): int
5026
    {
5027
        /**
5028
         * @psalm-suppress ImpureStaticVariable
5029
         *
5030
         * @var array<string,int>
5031
         */
5032 27
        static $CHAR_CACHE = [];
5033
5034
        // init
5035 27
        $chr = (string) $chr;
5036
5037 27
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
5038 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
5039
        }
5040
5041 27
        $cache_key = $chr . '_' . $encoding;
5042 27
        if (isset($CHAR_CACHE[$cache_key])) {
5043 27
            return $CHAR_CACHE[$cache_key];
5044
        }
5045
5046
        // check again, if it's still not UTF-8
5047 11
        if ($encoding !== 'UTF-8') {
5048 3
            $chr = self::encode($encoding, $chr);
5049
        }
5050
5051 11
        if (self::$ORD === null) {
5052
            self::$ORD = self::getData('ord');
5053
        }
5054
5055 11
        if (isset(self::$ORD[$chr])) {
5056 11
            return $CHAR_CACHE[$cache_key] = self::$ORD[$chr];
5057
        }
5058
5059
        //
5060
        // fallback via "IntlChar"
5061
        //
5062
5063 6
        if (self::$SUPPORT['intlChar'] === true) {
5064
            /** @noinspection PhpComposerExtensionStubsInspection */
5065 5
            $code = \IntlChar::ord($chr);
5066 5
            if ($code) {
5067 5
                return $CHAR_CACHE[$cache_key] = $code;
5068
            }
5069
        }
5070
5071
        //
5072
        // fallback via vanilla php
5073
        //
5074
5075
        /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
5076 1
        $chr = \unpack('C*', (string) \substr($chr, 0, 4));
5077
        /** @noinspection OffsetOperationsInspection */
5078 1
        $code = $chr ? $chr[1] : 0;
5079
5080
        /** @noinspection OffsetOperationsInspection */
5081 1
        if ($code >= 0xF0 && isset($chr[4])) {
5082
            /** @noinspection UnnecessaryCastingInspection */
5083
            /** @noinspection OffsetOperationsInspection */
5084
            return $CHAR_CACHE[$cache_key] = (int) ((($code - 0xF0) << 18) + (($chr[2] - 0x80) << 12) + (($chr[3] - 0x80) << 6) + $chr[4] - 0x80);
5085
        }
5086
5087
        /** @noinspection OffsetOperationsInspection */
5088 1
        if ($code >= 0xE0 && isset($chr[3])) {
5089
            /** @noinspection UnnecessaryCastingInspection */
5090
            /** @noinspection OffsetOperationsInspection */
5091 1
            return $CHAR_CACHE[$cache_key] = (int) ((($code - 0xE0) << 12) + (($chr[2] - 0x80) << 6) + $chr[3] - 0x80);
5092
        }
5093
5094
        /** @noinspection OffsetOperationsInspection */
5095 1
        if ($code >= 0xC0 && isset($chr[2])) {
5096
            /** @noinspection UnnecessaryCastingInspection */
5097
            /** @noinspection OffsetOperationsInspection */
5098 1
            return $CHAR_CACHE[$cache_key] = (int) ((($code - 0xC0) << 6) + $chr[2] - 0x80);
5099
        }
5100
5101
        return $CHAR_CACHE[$cache_key] = $code;
5102
    }
5103
5104
    /**
5105
     * Parses the string into an array (into the the second parameter).
5106
     *
5107
     * WARNING: Unlike "parse_str()", this method does not (re-)place variables in the current scope,
5108
     *          if the second parameter is not set!
5109
     *
5110
     * EXAMPLE: <code>
5111
     * UTF8::parse_str('Iñtërnâtiônéàlizætiøn=測試&arr[]=foo+測試&arr[]=ການທົດສອບ', $array);
5112
     * echo $array['Iñtërnâtiônéàlizætiøn']; // '測試'
5113
     * </code>
5114
     *
5115
     * @see http://php.net/manual/en/function.parse-str.php
5116
     *
5117
     * @param string $str        <p>The input string.</p>
5118
     * @param array  $result     <p>The result will be returned into this reference parameter.</p>
5119
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
5120
     *
5121
     * @psalm-pure
5122
     *
5123
     * @return bool
5124
     *              <p>Will return <strong>false</strong> if php can't parse the string and we haven't any $result.</p>
5125
     */
5126 2
    public static function parse_str(string $str, &$result, bool $clean_utf8 = false): bool
5127
    {
5128 2
        if ($clean_utf8) {
5129 2
            $str = self::clean($str);
5130
        }
5131
5132 2
        if (self::$SUPPORT['mbstring'] === true) {
5133 2
            $return = \mb_parse_str($str, $result);
5134
5135 2
            return $return !== false && $result !== [];
5136
        }
5137
5138
        /**
5139
         * @psalm-suppress ImpureFunctionCall - we use the second parameter, so we don't change variables by magic
5140
         */
5141
        \parse_str($str, $result);
5142
5143
        return $result !== [];
5144
    }
5145
5146
    /**
5147
     * Checks if \u modifier is available that enables Unicode support in PCRE.
5148
     *
5149
     * @psalm-pure
5150
     *
5151
     * @return bool
5152
     *              <p>
5153
     *              <strong>true</strong> if support is available,<br>
5154
     *              <strong>false</strong> otherwise
5155
     *              </p>
5156
     */
5157
    public static function pcre_utf8_support(): bool
5158
    {
5159
        /** @noinspection PhpUsageOfSilenceOperatorInspection */
5160
        return (bool) @\preg_match('//u', '');
5161
    }
5162
5163
    /**
5164
     * Create an array containing a range of UTF-8 characters.
5165
     *
5166
     * EXAMPLE: <code>UTF8::range('κ', 'ζ'); // array('κ', 'ι', 'θ', 'η', 'ζ',)</code>
5167
     *
5168
     * @param int|string $var1      <p>Numeric or hexadecimal code points, or a UTF-8 character to start from.</p>
5169
     * @param int|string $var2      <p>Numeric or hexadecimal code points, or a UTF-8 character to end at.</p>
5170
     * @param bool       $use_ctype <p>use ctype to detect numeric and hexadecimal, otherwise we will use a simple
5171
     *                              "is_numeric"</p>
5172
     * @param string     $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
5173
     * @param float|int  $step      [optional] <p>
5174
     *                              If a step value is given, it will be used as the
5175
     *                              increment between elements in the sequence. step
5176
     *                              should be given as a positive number. If not specified,
5177
     *                              step will default to 1.
5178
     *                              </p>
5179
     *
5180
     * @psalm-pure
5181
     *
5182
     * @return string[]
5183
     */
5184 2
    public static function range(
5185
        $var1,
5186
        $var2,
5187
        bool $use_ctype = true,
5188
        string $encoding = 'UTF-8',
5189
        $step = 1
5190
    ): array {
5191 2
        if (!$var1 || !$var2) {
5192 2
            return [];
5193
        }
5194
5195 2
        if ($step !== 1) {
5196
            /**
5197
             * @psalm-suppress RedundantConditionGivenDocblockType
5198
             * @psalm-suppress DocblockTypeContradiction
5199
             */
5200 1
            if (!\is_numeric($step)) {
0 ignored issues
show
introduced by
The condition is_numeric($step) is always true.
Loading history...
5201
                throw new \InvalidArgumentException('$step need to be a number, type given: ' . \gettype($step));
5202
            }
5203
5204
            /**
5205
             * @psalm-suppress RedundantConditionGivenDocblockType - false-positive from psalm?
5206
             */
5207 1
            if ($step <= 0) {
5208
                throw new \InvalidArgumentException('$step need to be a positive number, given: ' . $step);
5209
            }
5210
        }
5211
5212 2
        if ($use_ctype && self::$SUPPORT['ctype'] === false) {
5213
            throw new \RuntimeException('ext-ctype: is not installed');
5214
        }
5215
5216 2
        $is_digit = false;
5217 2
        $is_xdigit = false;
5218
5219
        /** @noinspection PhpComposerExtensionStubsInspection */
5220 2
        if ($use_ctype && \ctype_digit((string) $var1) && \ctype_digit((string) $var2)) {
5221 2
            $is_digit = true;
5222 2
            $start = (int) $var1;
5223 2
        } /** @noinspection PhpComposerExtensionStubsInspection */ elseif ($use_ctype && \ctype_xdigit($var1) && \ctype_xdigit($var2)) {
5224
            $is_xdigit = true;
5225
            $start = (int) self::hex_to_int((string) $var1);
5226 2
        } elseif (!$use_ctype && \is_numeric($var1)) {
5227 1
            $start = (int) $var1;
5228
        } else {
5229 2
            $start = self::ord((string) $var1);
5230
        }
5231
5232 2
        if (!$start) {
5233
            return [];
5234
        }
5235
5236 2
        if ($is_digit) {
5237 2
            $end = (int) $var2;
5238 2
        } elseif ($is_xdigit) {
5239
            $end = (int) self::hex_to_int((string) $var2);
5240 2
        } elseif (!$use_ctype && \is_numeric($var2)) {
5241 1
            $end = (int) $var2;
5242
        } else {
5243 2
            $end = self::ord((string) $var2);
5244
        }
5245
5246 2
        if (!$end) {
5247
            return [];
5248
        }
5249
5250 2
        $array = [];
5251 2
        foreach (\range($start, $end, $step) as $i) {
5252 2
            $array[] = (string) self::chr((int) $i, $encoding);
5253
        }
5254
5255 2
        return $array;
5256
    }
5257
5258
    /**
5259
     * Multi decode HTML entity + fix urlencoded-win1252-chars.
5260
     *
5261
     * EXAMPLE: <code>UTF8::rawurldecode('tes%20öäü%20\u00edtest+test'); // 'tes öäü ítest+test'</code>
5262
     *
5263
     * e.g:
5264
     * 'test+test'                     => 'test+test'
5265
     * 'D&#252;sseldorf'               => 'Düsseldorf'
5266
     * 'D%FCsseldorf'                  => 'Düsseldorf'
5267
     * 'D&#xFC;sseldorf'               => 'Düsseldorf'
5268
     * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
5269
     * 'Düsseldorf'                   => 'Düsseldorf'
5270
     * 'D%C3%BCsseldorf'               => 'Düsseldorf'
5271
     * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
5272
     * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
5273
     *
5274
     * @param string $str          <p>The input string.</p>
5275
     * @param bool   $multi_decode <p>Decode as often as possible.</p>
5276
     *
5277
     * @psalm-pure
5278
     *
5279
     * @return string
5280
     *                <p>The decoded URL, as a string.</p>
5281
     */
5282 7
    public static function rawurldecode(string $str, bool $multi_decode = true): string
5283
    {
5284 7
        if ($str === '') {
5285 4
            return '';
5286
        }
5287
5288
        if (
5289 7
            \strpos($str, '&') === false
5290
            &&
5291 7
            \strpos($str, '%') === false
5292
            &&
5293 7
            \strpos($str, '+') === false
5294
            &&
5295 7
            \strpos($str, '\u') === false
5296
        ) {
5297 4
            return self::fix_simple_utf8($str);
5298
        }
5299
5300 7
        $str = self::urldecode_unicode_helper($str);
5301
5302 7
        if ($multi_decode) {
5303
            do {
5304 6
                $str_compare = $str;
5305
5306
                /**
5307
                 * @psalm-suppress PossiblyInvalidArgument
5308
                 */
5309 6
                $str = self::fix_simple_utf8(
5310 6
                    \rawurldecode(
5311 6
                        self::html_entity_decode(
5312 6
                            self::to_utf8($str),
5313 6
                            \ENT_QUOTES | \ENT_HTML5
5314
                        )
5315
                    )
5316
                );
5317 6
            } while ($str_compare !== $str);
5318
        } else {
5319
            /**
5320
             * @psalm-suppress PossiblyInvalidArgument
5321
             */
5322 1
            $str = self::fix_simple_utf8(
5323 1
                \rawurldecode(
5324 1
                    self::html_entity_decode(
5325 1
                        self::to_utf8($str),
5326 1
                        \ENT_QUOTES | \ENT_HTML5
5327
                    )
5328
                )
5329
            );
5330
        }
5331
5332 7
        return $str;
5333
    }
5334
5335
    /**
5336
     * Replaces all occurrences of $pattern in $str by $replacement.
5337
     *
5338
     * @param string $str         <p>The input string.</p>
5339
     * @param string $pattern     <p>The regular expression pattern.</p>
5340
     * @param string $replacement <p>The string to replace with.</p>
5341
     * @param string $options     [optional] <p>Matching conditions to be used.</p>
5342
     * @param string $delimiter   [optional] <p>Delimiter the the regex. Default: '/'</p>
5343
     *
5344
     * @psalm-pure
5345
     *
5346
     * @return string
5347
     */
5348 18
    public static function regex_replace(
5349
        string $str,
5350
        string $pattern,
5351
        string $replacement,
5352
        string $options = '',
5353
        string $delimiter = '/'
5354
    ): string {
5355 18
        if ($options === 'msr') {
5356 9
            $options = 'ms';
5357
        }
5358
5359
        // fallback
5360 18
        if (!$delimiter) {
5361
            $delimiter = '/';
5362
        }
5363
5364 18
        return (string) \preg_replace(
5365 18
            $delimiter . $pattern . $delimiter . 'u' . $options,
5366 18
            $replacement,
5367 18
            $str
5368
        );
5369
    }
5370
5371
    /**
5372
     * alias for "UTF8::remove_bom()"
5373
     *
5374
     * @param string $str
5375
     *
5376
     * @psalm-pure
5377
     *
5378
     * @return string
5379
     *
5380
     * @see        UTF8::remove_bom()
5381
     * @deprecated <p>please use "UTF8::remove_bom()"</p>
5382
     */
5383 1
    public static function removeBOM(string $str): string
5384
    {
5385 1
        return self::remove_bom($str);
5386
    }
5387
5388
    /**
5389
     * Remove the BOM from UTF-8 / UTF-16 / UTF-32 strings.
5390
     *
5391
     * EXAMPLE: <code>UTF8::remove_bom("\xEF\xBB\xBFΜπορώ να"); // 'Μπορώ να'</code>
5392
     *
5393
     * @param string $str <p>The input string.</p>
5394
     *
5395
     * @psalm-pure
5396
     *
5397
     * @return string
5398
     *                <p>A string without UTF-BOM.</p>
5399
     */
5400 55
    public static function remove_bom(string $str): string
5401
    {
5402 55
        if ($str === '') {
5403 9
            return '';
5404
        }
5405
5406 55
        $str_length = \strlen($str);
5407 55
        foreach (self::$BOM as $bom_string => $bom_byte_length) {
5408 55
            if (\strncmp($str, $bom_string, $bom_byte_length) === 0) {
5409
                /** @var false|string $str_tmp - needed for PhpStan (stubs error) */
5410 11
                $str_tmp = \substr($str, $bom_byte_length, $str_length);
5411 11
                if ($str_tmp === false) {
5412
                    return '';
5413
                }
5414
5415 11
                $str_length -= (int) $bom_byte_length;
5416
5417 55
                $str = (string) $str_tmp;
5418
            }
5419
        }
5420
5421 55
        return $str;
5422
    }
5423
5424
    /**
5425
     * Removes duplicate occurrences of a string in another string.
5426
     *
5427
     * EXAMPLE: <code>UTF8::remove_duplicates('öäü-κόσμεκόσμε-äöü', 'κόσμε'); // 'öäü-κόσμε-äöü'</code>
5428
     *
5429
     * @param string          $str  <p>The base string.</p>
5430
     * @param string|string[] $what <p>String to search for in the base string.</p>
5431
     *
5432
     * @psalm-pure
5433
     *
5434
     * @return string
5435
     *                <p>A string with removed duplicates.</p>
5436
     */
5437 2
    public static function remove_duplicates(string $str, $what = ' '): string
5438
    {
5439 2
        if (\is_string($what)) {
5440 2
            $what = [$what];
5441
        }
5442
5443
        /**
5444
         * @psalm-suppress RedundantConditionGivenDocblockType
5445
         */
5446 2
        if (\is_array($what)) {
0 ignored issues
show
introduced by
The condition is_array($what) is always true.
Loading history...
5447 2
            foreach ($what as $item) {
5448 2
                $str = (string) \preg_replace('/(' . \preg_quote($item, '/') . ')+/u', $item, $str);
5449
            }
5450
        }
5451
5452 2
        return $str;
5453
    }
5454
5455
    /**
5456
     * Remove html via "strip_tags()" from the string.
5457
     *
5458
     * @param string $str            <p>The input string.</p>
5459
     * @param string $allowable_tags [optional] <p>You can use the optional second parameter to specify tags which
5460
     *                               should not be stripped. Default: null
5461
     *                               </p>
5462
     *
5463
     * @psalm-pure
5464
     *
5465
     * @return string
5466
     *                <p>A string with without html tags.</p>
5467
     */
5468 6
    public static function remove_html(string $str, string $allowable_tags = ''): string
5469
    {
5470 6
        return \strip_tags($str, $allowable_tags);
5471
    }
5472
5473
    /**
5474
     * Remove all breaks [<br> | \r\n | \r | \n | ...] from the string.
5475
     *
5476
     * @param string $str         <p>The input string.</p>
5477
     * @param string $replacement [optional] <p>Default is a empty string.</p>
5478
     *
5479
     * @psalm-pure
5480
     *
5481
     * @return string
5482
     *                <p>A string without breaks.</p>
5483
     */
5484 6
    public static function remove_html_breaks(string $str, string $replacement = ''): string
5485
    {
5486 6
        return (string) \preg_replace("#/\r\n|\r|\n|<br.*/?>#isU", $replacement, $str);
5487
    }
5488
5489
    /**
5490
     * Remove invisible characters from a string.
5491
     *
5492
     * e.g.: This prevents sandwiching null characters between ascii characters, like Java\0script.
5493
     *
5494
     * EXAMPLE: <code>UTF8::remove_invisible_characters("κόσ\0με"); // 'κόσμε'</code>
5495
     *
5496
     * copy&past from https://github.com/bcit-ci/CodeIgniter/blob/develop/system/core/Common.php
5497
     *
5498
     * @param string $str         <p>The input string.</p>
5499
     * @param bool   $url_encoded [optional] <p>
5500
     *                            Try to remove url encoded control character.
5501
     *                            WARNING: maybe contains false-positives e.g. aa%0Baa -> aaaa.
5502
     *                            <br>
5503
     *                            Default: false
5504
     *                            </p>
5505
     * @param string $replacement [optional] <p>The replacement character.</p>
5506
     *
5507
     * @psalm-pure
5508
     *
5509
     * @return string
5510
     *                <p>A string without invisible chars.</p>
5511
     */
5512 92
    public static function remove_invisible_characters(
5513
        string $str,
5514
        bool $url_encoded = false,
5515
        string $replacement = ''
5516
    ): string {
5517 92
        return ASCII::remove_invisible_characters(
5518 92
            $str,
5519 92
            $url_encoded,
5520 92
            $replacement
5521
        );
5522
    }
5523
5524
    /**
5525
     * Returns a new string with the prefix $substring removed, if present.
5526
     *
5527
     * @param string $str       <p>The input string.</p>
5528
     * @param string $substring <p>The prefix to remove.</p>
5529
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
5530
     *
5531
     * @psalm-pure
5532
     *
5533
     * @return string
5534
     *                <p>A string without the prefix $substring.</p>
5535
     */
5536 12
    public static function remove_left(
5537
        string $str,
5538
        string $substring,
5539
        string $encoding = 'UTF-8'
5540
    ): string {
5541
        if (
5542 12
            $substring
5543
            &&
5544 12
            \strpos($str, $substring) === 0
5545
        ) {
5546 6
            if ($encoding === 'UTF-8') {
5547 4
                return (string) \mb_substr(
5548 4
                    $str,
5549 4
                    (int) \mb_strlen($substring)
5550
                );
5551
            }
5552
5553 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
5554
5555 2
            return (string) self::substr(
5556 2
                $str,
5557 2
                (int) self::strlen($substring, $encoding),
5558 2
                null,
5559 2
                $encoding
5560
            );
5561
        }
5562
5563 6
        return $str;
5564
    }
5565
5566
    /**
5567
     * Returns a new string with the suffix $substring removed, if present.
5568
     *
5569
     * @param string $str
5570
     * @param string $substring <p>The suffix to remove.</p>
5571
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
5572
     *
5573
     * @psalm-pure
5574
     *
5575
     * @return string
5576
     *                <p>A string having a $str without the suffix $substring.</p>
5577
     */
5578 12
    public static function remove_right(
5579
        string $str,
5580
        string $substring,
5581
        string $encoding = 'UTF-8'
5582
    ): string {
5583 12
        if ($substring && \substr($str, -\strlen($substring)) === $substring) {
5584 6
            if ($encoding === 'UTF-8') {
5585 4
                return (string) \mb_substr(
5586 4
                    $str,
5587 4
                    0,
5588 4
                    (int) \mb_strlen($str) - (int) \mb_strlen($substring)
5589
                );
5590
            }
5591
5592 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
5593
5594 2
            return (string) self::substr(
5595 2
                $str,
5596 2
                0,
5597 2
                (int) self::strlen($str, $encoding) - (int) self::strlen($substring, $encoding),
5598 2
                $encoding
5599
            );
5600
        }
5601
5602 6
        return $str;
5603
    }
5604
5605
    /**
5606
     * Replaces all occurrences of $search in $str by $replacement.
5607
     *
5608
     * @param string $str            <p>The input string.</p>
5609
     * @param string $search         <p>The needle to search for.</p>
5610
     * @param string $replacement    <p>The string to replace with.</p>
5611
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5612
     *
5613
     * @psalm-pure
5614
     *
5615
     * @return string
5616
     *                <p>A string with replaced parts.</p>
5617
     */
5618 29
    public static function replace(
5619
        string $str,
5620
        string $search,
5621
        string $replacement,
5622
        bool $case_sensitive = true
5623
    ): string {
5624 29
        if ($case_sensitive) {
5625 22
            return \str_replace($search, $replacement, $str);
5626
        }
5627
5628 7
        return self::str_ireplace($search, $replacement, $str);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::str_ireplac...ch, $replacement, $str) 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...
5629
    }
5630
5631
    /**
5632
     * Replaces all occurrences of $search in $str by $replacement.
5633
     *
5634
     * @param string       $str            <p>The input string.</p>
5635
     * @param array        $search         <p>The elements to search for.</p>
5636
     * @param array|string $replacement    <p>The string to replace with.</p>
5637
     * @param bool         $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5638
     *
5639
     * @psalm-pure
5640
     *
5641
     * @return string
5642
     *                <p>A string with replaced parts.</p>
5643
     */
5644 30
    public static function replace_all(
5645
        string $str,
5646
        array $search,
5647
        $replacement,
5648
        bool $case_sensitive = true
5649
    ): string {
5650 30
        if ($case_sensitive) {
5651 23
            return \str_replace($search, $replacement, $str);
5652
        }
5653
5654 7
        return self::str_ireplace($search, $replacement, $str);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::str_ireplac...ch, $replacement, $str) 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...
5655
    }
5656
5657
    /**
5658
     * Replace the diamond question mark (�) and invalid-UTF8 chars with the replacement.
5659
     *
5660
     * EXAMPLE: <code>UTF8::replace_diamond_question_mark('中文空白�', ''); // '中文空白'</code>
5661
     *
5662
     * @param string $str                        <p>The input string</p>
5663
     * @param string $replacement_char           <p>The replacement character.</p>
5664
     * @param bool   $process_invalid_utf8_chars <p>Convert invalid UTF-8 chars </p>
5665
     *
5666
     * @psalm-pure
5667
     *
5668
     * @return string
5669
     *                <p>A string without diamond question marks (�).</p>
5670
     */
5671 35
    public static function replace_diamond_question_mark(
5672
        string $str,
5673
        string $replacement_char = '',
5674
        bool $process_invalid_utf8_chars = true
5675
    ): string {
5676 35
        if ($str === '') {
5677 9
            return '';
5678
        }
5679
5680 35
        if ($process_invalid_utf8_chars) {
5681 35
            if ($replacement_char === '') {
5682 35
                $replacement_char_helper = 'none';
5683
            } else {
5684 2
                $replacement_char_helper = \ord($replacement_char);
5685
            }
5686
5687 35
            if (self::$SUPPORT['mbstring'] === false) {
5688
                // if there is no native support for "mbstring",
5689
                // then we need to clean the string before ...
5690
                $str = self::clean($str);
5691
            }
5692
5693
            /**
5694
             * @psalm-suppress ImpureFunctionCall - we will reset the value in the next step
5695
             */
5696 35
            $save = \mb_substitute_character();
5697
            /** @noinspection PhpUsageOfSilenceOperatorInspection - ignore "Unknown character" warnings, it's working anyway */
5698 35
            @\mb_substitute_character($replacement_char_helper);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mb_substitute_character(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

5698
            /** @scrutinizer ignore-unhandled */ @\mb_substitute_character($replacement_char_helper);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
5699
            // the polyfill maybe return false, so cast to string
5700 35
            $str = (string) \mb_convert_encoding($str, 'UTF-8', 'UTF-8');
5701 35
            \mb_substitute_character($save);
5702
        }
5703
5704 35
        return \str_replace(
5705
            [
5706 35
                "\xEF\xBF\xBD",
5707
                '�',
5708
            ],
5709
            [
5710 35
                $replacement_char,
5711 35
                $replacement_char,
5712
            ],
5713 35
            $str
5714
        );
5715
    }
5716
5717
    /**
5718
     * Strip whitespace or other characters from the end of a UTF-8 string.
5719
     *
5720
     * EXAMPLE: <code>UTF8::rtrim('-ABC-中文空白-  '); // '-ABC-中文空白-'</code>
5721
     *
5722
     * @param string      $str   <p>The string to be trimmed.</p>
5723
     * @param string|null $chars <p>Optional characters to be stripped.</p>
5724
     *
5725
     * @psalm-pure
5726
     *
5727
     * @return string
5728
     *                <p>A string with unwanted characters stripped from the right.</p>
5729
     */
5730 21
    public static function rtrim(string $str = '', string $chars = null): string
5731
    {
5732 21
        if ($str === '') {
5733 3
            return '';
5734
        }
5735
5736 20
        if (self::$SUPPORT['mbstring'] === true) {
5737 20
            if ($chars !== null) {
5738
                /** @noinspection PregQuoteUsageInspection */
5739 9
                $chars = \preg_quote($chars);
5740 9
                $pattern = "[${chars}]+$";
5741
            } else {
5742 14
                $pattern = '[\\s]+$';
5743
            }
5744
5745
            /** @noinspection PhpComposerExtensionStubsInspection */
5746 20
            return (string) \mb_ereg_replace($pattern, '', $str);
5747
        }
5748
5749
        if ($chars !== null) {
5750
            $chars = \preg_quote($chars, '/');
5751
            $pattern = "[${chars}]+$";
5752
        } else {
5753
            $pattern = '[\\s]+$';
5754
        }
5755
5756
        return self::regex_replace($str, $pattern, '');
5757
    }
5758
5759
    /**
5760
     * WARNING: Print native UTF-8 support (libs) by default, e.g. for debugging.
5761
     *
5762
     * @param bool $useEcho
5763
     *
5764
     * @psalm-pure
5765
     *
5766
     * @return string|void
5767
     */
5768 2
    public static function showSupport(bool $useEcho = true)
5769
    {
5770
        // init
5771 2
        $html = '';
5772
5773 2
        $html .= '<pre>';
5774
        /** @noinspection AlterInForeachInspection */
5775 2
        foreach (self::$SUPPORT as $key => &$value) {
5776 2
            $html .= $key . ' - ' . \print_r($value, true) . "\n<br>";
5777
        }
5778 2
        $html .= '</pre>';
5779
5780 2
        if ($useEcho) {
5781 1
            echo $html;
5782
        }
5783
5784 2
        return $html;
5785
    }
5786
5787
    /**
5788
     * Converts a UTF-8 character to HTML Numbered Entity like "&#123;".
5789
     *
5790
     * EXAMPLE: <code>UTF8::single_chr_html_encode('κ'); // '&#954;'</code>
5791
     *
5792
     * @param string $char             <p>The Unicode character to be encoded as numbered entity.</p>
5793
     * @param bool   $keep_ascii_chars <p>Set to <strong>true</strong> to keep ASCII chars.</>
5794
     * @param string $encoding         [optional] <p>Set the charset for e.g. "mb_" function</p>
5795
     *
5796
     * @psalm-pure
5797
     *
5798
     * @return string
5799
     *                <p>The HTML numbered entity for the given character.</p>
5800
     */
5801 2
    public static function single_chr_html_encode(
5802
        string $char,
5803
        bool $keep_ascii_chars = false,
5804
        string $encoding = 'UTF-8'
5805
    ): string {
5806 2
        if ($char === '') {
5807 2
            return '';
5808
        }
5809
5810
        if (
5811 2
            $keep_ascii_chars
5812
            &&
5813 2
            ASCII::is_ascii($char)
5814
        ) {
5815 2
            return $char;
5816
        }
5817
5818 2
        return '&#' . self::ord($char, $encoding) . ';';
5819
    }
5820
5821
    /**
5822
     * @param string $str
5823
     * @param int    $tab_length
5824
     *
5825
     * @psalm-pure
5826
     *
5827
     * @return string
5828
     */
5829 5
    public static function spaces_to_tabs(string $str, int $tab_length = 4): string
5830
    {
5831 5
        if ($tab_length === 4) {
5832 3
            $tab = '    ';
5833 2
        } elseif ($tab_length === 2) {
5834 1
            $tab = '  ';
5835
        } else {
5836 1
            $tab = \str_repeat(' ', $tab_length);
5837
        }
5838
5839 5
        return \str_replace($tab, "\t", $str);
5840
    }
5841
5842
    /**
5843
     * alias for "UTF8::str_split()"
5844
     *
5845
     * @param int|string $str
5846
     * @param int        $length
5847
     * @param bool       $clean_utf8
5848
     *
5849
     * @psalm-pure
5850
     *
5851
     * @return string[]
5852
     *
5853
     * @see        UTF8::str_split()
5854
     * @deprecated <p>please use "UTF8::str_split()"</p>
5855
     */
5856 9
    public static function split(
5857
        $str,
5858
        int $length = 1,
5859
        bool $clean_utf8 = false
5860
    ): array {
5861
        /** @var string[] */
5862 9
        return self::str_split($str, $length, $clean_utf8);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::str_split($str, $length, $clean_utf8) returns an array which contains values of type array|string[] which are incompatible with the documented value type string.
Loading history...
5863
    }
5864
5865
    /**
5866
     * alias for "UTF8::str_starts_with()"
5867
     *
5868
     * @param string $haystack
5869
     * @param string $needle
5870
     *
5871
     * @psalm-pure
5872
     *
5873
     * @return bool
5874
     *
5875
     * @see        UTF8::str_starts_with()
5876
     * @deprecated <p>please use "UTF8::str_starts_with()"</p>
5877
     */
5878 1
    public static function str_begins(string $haystack, string $needle): bool
5879
    {
5880 1
        return self::str_starts_with($haystack, $needle);
5881
    }
5882
5883
    /**
5884
     * Returns a camelCase version of the string. Trims surrounding spaces,
5885
     * capitalizes letters following digits, spaces, dashes and underscores,
5886
     * and removes spaces, dashes, as well as underscores.
5887
     *
5888
     * @param string      $str                           <p>The input string.</p>
5889
     * @param string      $encoding                      [optional] <p>Default: 'UTF-8'</p>
5890
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
5891
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
5892
     *                                                   tr</p>
5893
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
5894
     *                                                   -> ß</p>
5895
     *
5896
     * @psalm-pure
5897
     *
5898
     * @return string
5899
     */
5900 32
    public static function str_camelize(
5901
        string $str,
5902
        string $encoding = 'UTF-8',
5903
        bool $clean_utf8 = false,
5904
        string $lang = null,
5905
        bool $try_to_keep_the_string_length = false
5906
    ): string {
5907 32
        if ($clean_utf8) {
5908
            $str = self::clean($str);
5909
        }
5910
5911 32
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
5912 26
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
5913
        }
5914
5915 32
        $str = self::lcfirst(
5916 32
            \trim($str),
5917 32
            $encoding,
5918 32
            false,
5919 32
            $lang,
5920 32
            $try_to_keep_the_string_length
5921
        );
5922 32
        $str = (string) \preg_replace('/^[-_]+/', '', $str);
5923
5924 32
        $use_mb_functions = $lang === null && !$try_to_keep_the_string_length;
5925
5926 32
        $str = (string) \preg_replace_callback(
5927 32
            '/[-_\\s]+(.)?/u',
5928
            /**
5929
             * @param array $match
5930
             *
5931
             * @psalm-pure
5932
             *
5933
             * @return string
5934
             */
5935
            static function (array $match) use ($use_mb_functions, $encoding, $lang, $try_to_keep_the_string_length): string {
5936 27
                if (isset($match[1])) {
5937 27
                    if ($use_mb_functions) {
5938 27
                        if ($encoding === 'UTF-8') {
5939 27
                            return \mb_strtoupper($match[1]);
5940
                        }
5941
5942
                        return \mb_strtoupper($match[1], $encoding);
5943
                    }
5944
5945
                    return self::strtoupper($match[1], $encoding, false, $lang, $try_to_keep_the_string_length);
5946
                }
5947
5948 1
                return '';
5949 32
            },
5950 32
            $str
5951
        );
5952
5953 32
        return (string) \preg_replace_callback(
5954 32
            '/[\\p{N}]+(.)?/u',
5955
            /**
5956
             * @param array $match
5957
             *
5958
             * @psalm-pure
5959
             *
5960
             * @return string
5961
             */
5962
            static function (array $match) use ($use_mb_functions, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length): string {
5963 6
                if ($use_mb_functions) {
5964 6
                    if ($encoding === 'UTF-8') {
5965 6
                        return \mb_strtoupper($match[0]);
5966
                    }
5967
5968
                    return \mb_strtoupper($match[0], $encoding);
5969
                }
5970
5971
                return self::strtoupper($match[0], $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
5972 32
            },
5973 32
            $str
5974
        );
5975
    }
5976
5977
    /**
5978
     * Returns the string with the first letter of each word capitalized,
5979
     * except for when the word is a name which shouldn't be capitalized.
5980
     *
5981
     * @param string $str
5982
     *
5983
     * @psalm-pure
5984
     *
5985
     * @return string
5986
     *                <p>A string with $str capitalized.</p>
5987
     */
5988 1
    public static function str_capitalize_name(string $str): string
5989
    {
5990 1
        return self::str_capitalize_name_helper(
5991 1
            self::str_capitalize_name_helper(
5992 1
                self::collapse_whitespace($str),
5993 1
                ' '
5994
            ),
5995 1
            '-'
5996
        );
5997
    }
5998
5999
    /**
6000
     * Returns true if the string contains $needle, false otherwise. By default
6001
     * the comparison is case-sensitive, but can be made insensitive by setting
6002
     * $case_sensitive to false.
6003
     *
6004
     * @param string $haystack       <p>The input string.</p>
6005
     * @param string $needle         <p>Substring to look for.</p>
6006
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
6007
     *
6008
     * @psalm-pure
6009
     *
6010
     * @return bool
6011
     *              <p>Whether or not $haystack contains $needle.</p>
6012
     */
6013 21
    public static function str_contains(
6014
        string $haystack,
6015
        string $needle,
6016
        bool $case_sensitive = true
6017
    ): bool {
6018 21
        if ($case_sensitive) {
6019 11
            return \strpos($haystack, $needle) !== false;
6020
        }
6021
6022 10
        return \mb_stripos($haystack, $needle) !== false;
6023
    }
6024
6025
    /**
6026
     * Returns true if the string contains all $needles, false otherwise. By
6027
     * default the comparison is case-sensitive, but can be made insensitive by
6028
     * setting $case_sensitive to false.
6029
     *
6030
     * @param string $haystack       <p>The input string.</p>
6031
     * @param array  $needles        <p>SubStrings to look for.</p>
6032
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
6033
     *
6034
     * @psalm-pure
6035
     *
6036
     * @return bool
6037
     *              <p>Whether or not $haystack contains $needle.</p>
6038
     */
6039 45
    public static function str_contains_all(
6040
        string $haystack,
6041
        array $needles,
6042
        bool $case_sensitive = true
6043
    ): bool {
6044 45
        if ($haystack === '' || $needles === []) {
6045 1
            return false;
6046
        }
6047
6048
        /** @noinspection LoopWhichDoesNotLoopInspection */
6049 44
        foreach ($needles as &$needle) {
6050 44
            if ($case_sensitive) {
6051
                /** @noinspection NestedPositiveIfStatementsInspection */
6052 24
                if (!$needle || \strpos($haystack, $needle) === false) {
6053 12
                    return false;
6054
                }
6055
            }
6056
6057 33
            if (!$needle || \mb_stripos($haystack, $needle) === false) {
6058 33
                return false;
6059
            }
6060
        }
6061
6062 24
        return true;
6063
    }
6064
6065
    /**
6066
     * Returns true if the string contains any $needles, false otherwise. By
6067
     * default the comparison is case-sensitive, but can be made insensitive by
6068
     * setting $case_sensitive to false.
6069
     *
6070
     * @param string $haystack       <p>The input string.</p>
6071
     * @param array  $needles        <p>SubStrings to look for.</p>
6072
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
6073
     *
6074
     * @psalm-pure
6075
     *
6076
     * @return bool
6077
     *              <p>Whether or not $str contains $needle.</p>
6078
     */
6079 46
    public static function str_contains_any(
6080
        string $haystack,
6081
        array $needles,
6082
        bool $case_sensitive = true
6083
    ): bool {
6084 46
        if ($haystack === '' || $needles === []) {
6085 1
            return false;
6086
        }
6087
6088
        /** @noinspection LoopWhichDoesNotLoopInspection */
6089 45
        foreach ($needles as &$needle) {
6090 45
            if (!$needle) {
6091
                continue;
6092
            }
6093
6094 45
            if ($case_sensitive) {
6095 25
                if (\strpos($haystack, $needle) !== false) {
6096 14
                    return true;
6097
                }
6098
6099 13
                continue;
6100
            }
6101
6102 20
            if (\mb_stripos($haystack, $needle) !== false) {
6103 20
                return true;
6104
            }
6105
        }
6106
6107 19
        return false;
6108
    }
6109
6110
    /**
6111
     * Returns a lowercase and trimmed string separated by dashes. Dashes are
6112
     * inserted before uppercase characters (with the exception of the first
6113
     * character of the string), and in place of spaces as well as underscores.
6114
     *
6115
     * @param string $str      <p>The input string.</p>
6116
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6117
     *
6118
     * @psalm-pure
6119
     *
6120
     * @return string
6121
     */
6122 19
    public static function str_dasherize(string $str, string $encoding = 'UTF-8'): string
6123
    {
6124 19
        return self::str_delimit($str, '-', $encoding);
6125
    }
6126
6127
    /**
6128
     * Returns a lowercase and trimmed string separated by the given delimiter.
6129
     * Delimiters are inserted before uppercase characters (with the exception
6130
     * of the first character of the string), and in place of spaces, dashes,
6131
     * and underscores. Alpha delimiters are not converted to lowercase.
6132
     *
6133
     * @param string      $str                           <p>The input string.</p>
6134
     * @param string      $delimiter                     <p>Sequence used to separate parts of the string.</p>
6135
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
6136
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
6137
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
6138
     *                                                   tr</p>
6139
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ ->
6140
     *                                                   ß</p>
6141
     *
6142
     * @psalm-pure
6143
     *
6144
     * @return string
6145
     */
6146 49
    public static function str_delimit(
6147
        string $str,
6148
        string $delimiter,
6149
        string $encoding = 'UTF-8',
6150
        bool $clean_utf8 = false,
6151
        string $lang = null,
6152
        bool $try_to_keep_the_string_length = false
6153
    ): string {
6154 49
        if (self::$SUPPORT['mbstring'] === true) {
6155
            /** @noinspection PhpComposerExtensionStubsInspection */
6156 49
            $str = (string) \mb_ereg_replace('\\B(\\p{Lu})', '-\1', \trim($str));
6157
6158 49
            $use_mb_functions = $lang === null && !$try_to_keep_the_string_length;
6159 49
            if ($use_mb_functions && $encoding === 'UTF-8') {
6160 22
                $str = \mb_strtolower($str);
6161
            } else {
6162 27
                $str = self::strtolower($str, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
6163
            }
6164
6165
            /** @noinspection PhpComposerExtensionStubsInspection */
6166 49
            return (string) \mb_ereg_replace('[\\-_\\s]+', $delimiter, $str);
6167
        }
6168
6169
        $str = (string) \preg_replace('/\\B(\\p{Lu})/u', '-\1', \trim($str));
6170
6171
        $use_mb_functions = $lang === null && !$try_to_keep_the_string_length;
6172
        if ($use_mb_functions && $encoding === 'UTF-8') {
6173
            $str = \mb_strtolower($str);
6174
        } else {
6175
            $str = self::strtolower($str, $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
6176
        }
6177
6178
        return (string) \preg_replace('/[\\-_\\s]+/u', $delimiter, $str);
6179
    }
6180
6181
    /**
6182
     * Optimized "mb_detect_encoding()"-function -> with support for UTF-16 and UTF-32.
6183
     *
6184
     * EXAMPLE: <code>
6185
     * UTF8::str_detect_encoding('中文空白'); // 'UTF-8'
6186
     * UTF8::str_detect_encoding('Abc'); // 'ASCII'
6187
     * </code>
6188
     *
6189
     * @param string $str <p>The input string.</p>
6190
     *
6191
     * @psalm-pure
6192
     *
6193
     * @return false|string
6194
     *                      <p>
6195
     *                      The detected string-encoding e.g. UTF-8 or UTF-16BE,<br>
6196
     *                      otherwise it will return false e.g. for BINARY or not detected encoding.
6197
     *                      </p>
6198
     */
6199 31
    public static function str_detect_encoding($str)
6200
    {
6201
        // init
6202 31
        $str = (string) $str;
6203
6204
        //
6205
        // 1.) check binary strings (010001001...) like UTF-16 / UTF-32 / PDF / Images / ...
6206
        //
6207
6208 31
        if (self::is_binary($str, true)) {
6209 11
            $is_utf32 = self::is_utf32($str, false);
6210 11
            if ($is_utf32 === 1) {
6211
                return 'UTF-32LE';
6212
            }
6213 11
            if ($is_utf32 === 2) {
6214 1
                return 'UTF-32BE';
6215
            }
6216
6217 11
            $is_utf16 = self::is_utf16($str, false);
6218 11
            if ($is_utf16 === 1) {
6219 3
                return 'UTF-16LE';
6220
            }
6221 11
            if ($is_utf16 === 2) {
6222 2
                return 'UTF-16BE';
6223
            }
6224
6225
            // is binary but not "UTF-16" or "UTF-32"
6226 9
            return false;
6227
        }
6228
6229
        //
6230
        // 2.) simple check for ASCII chars
6231
        //
6232
6233 27
        if (ASCII::is_ascii($str)) {
6234 10
            return 'ASCII';
6235
        }
6236
6237
        //
6238
        // 3.) simple check for UTF-8 chars
6239
        //
6240
6241 27
        if (self::is_utf8_string($str)) {
6242 19
            return 'UTF-8';
6243
        }
6244
6245
        //
6246
        // 4.) check via "mb_detect_encoding()"
6247
        //
6248
        // INFO: UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always with "mb_detect_encoding()"
6249
6250
        $encoding_detecting_order = [
6251 16
            'ISO-8859-1',
6252
            'ISO-8859-2',
6253
            'ISO-8859-3',
6254
            'ISO-8859-4',
6255
            'ISO-8859-5',
6256
            'ISO-8859-6',
6257
            'ISO-8859-7',
6258
            'ISO-8859-8',
6259
            'ISO-8859-9',
6260
            'ISO-8859-10',
6261
            'ISO-8859-13',
6262
            'ISO-8859-14',
6263
            'ISO-8859-15',
6264
            'ISO-8859-16',
6265
            'WINDOWS-1251',
6266
            'WINDOWS-1252',
6267
            'WINDOWS-1254',
6268
            'CP932',
6269
            'CP936',
6270
            'CP950',
6271
            'CP866',
6272
            'CP850',
6273
            'CP51932',
6274
            'CP50220',
6275
            'CP50221',
6276
            'CP50222',
6277
            'ISO-2022-JP',
6278
            'ISO-2022-KR',
6279
            'JIS',
6280
            'JIS-ms',
6281
            'EUC-CN',
6282
            'EUC-JP',
6283
        ];
6284
6285 16
        if (self::$SUPPORT['mbstring'] === true) {
6286
            // info: do not use the symfony polyfill here
6287 16
            $encoding = \mb_detect_encoding($str, $encoding_detecting_order, true);
6288 16
            if ($encoding) {
6289 16
                return $encoding;
6290
            }
6291
        }
6292
6293
        //
6294
        // 5.) check via "iconv()"
6295
        //
6296
6297
        if (self::$ENCODINGS === null) {
6298
            self::$ENCODINGS = self::getData('encodings');
6299
        }
6300
6301
        foreach (self::$ENCODINGS as $encoding_tmp) {
6302
            // INFO: //IGNORE but still throw notice
6303
            /** @noinspection PhpUsageOfSilenceOperatorInspection */
6304
            if ((string) @\iconv($encoding_tmp, $encoding_tmp . '//IGNORE', $str) === $str) {
6305
                return $encoding_tmp;
6306
            }
6307
        }
6308
6309
        return false;
6310
    }
6311
6312
    /**
6313
     * alias for "UTF8::str_ends_with()"
6314
     *
6315
     * @param string $haystack
6316
     * @param string $needle
6317
     *
6318
     * @psalm-pure
6319
     *
6320
     * @return bool
6321
     *
6322
     * @see        UTF8::str_ends_with()
6323
     * @deprecated <p>please use "UTF8::str_ends_with()"</p>
6324
     */
6325 1
    public static function str_ends(string $haystack, string $needle): bool
6326
    {
6327 1
        return self::str_ends_with($haystack, $needle);
6328
    }
6329
6330
    /**
6331
     * Check if the string ends with the given substring.
6332
     *
6333
     * EXAMPLE: <code>
6334
     * UTF8::str_ends_with('BeginMiddleΚόσμε', 'Κόσμε'); // true
6335
     * UTF8::str_ends_with('BeginMiddleΚόσμε', 'κόσμε'); // false
6336
     * </code>
6337
     *
6338
     * @param string $haystack <p>The string to search in.</p>
6339
     * @param string $needle   <p>The substring to search for.</p>
6340
     *
6341
     * @psalm-pure
6342
     *
6343
     * @return bool
6344
     */
6345 9
    public static function str_ends_with(string $haystack, string $needle): bool
6346
    {
6347 9
        if ($needle === '') {
6348 2
            return true;
6349
        }
6350
6351 9
        if ($haystack === '') {
6352
            return false;
6353
        }
6354
6355 9
        return \substr($haystack, -\strlen($needle)) === $needle;
6356
    }
6357
6358
    /**
6359
     * Returns true if the string ends with any of $substrings, false otherwise.
6360
     *
6361
     * - case-sensitive
6362
     *
6363
     * @param string   $str        <p>The input string.</p>
6364
     * @param string[] $substrings <p>Substrings to look for.</p>
6365
     *
6366
     * @psalm-pure
6367
     *
6368
     * @return bool
6369
     *              <p>Whether or not $str ends with $substring.</p>
6370
     */
6371 7
    public static function str_ends_with_any(string $str, array $substrings): bool
6372
    {
6373 7
        if ($substrings === []) {
6374
            return false;
6375
        }
6376
6377 7
        foreach ($substrings as &$substring) {
6378 7
            if (\substr($str, -\strlen($substring)) === $substring) {
6379 7
                return true;
6380
            }
6381
        }
6382
6383 6
        return false;
6384
    }
6385
6386
    /**
6387
     * Ensures that the string begins with $substring. If it doesn't, it's
6388
     * prepended.
6389
     *
6390
     * @param string $str       <p>The input string.</p>
6391
     * @param string $substring <p>The substring to add if not present.</p>
6392
     *
6393
     * @psalm-pure
6394
     *
6395
     * @return string
6396
     */
6397 10
    public static function str_ensure_left(string $str, string $substring): string
6398
    {
6399
        if (
6400 10
            $substring !== ''
6401
            &&
6402 10
            \strpos($str, $substring) === 0
6403
        ) {
6404 6
            return $str;
6405
        }
6406
6407 4
        return $substring . $str;
6408
    }
6409
6410
    /**
6411
     * Ensures that the string ends with $substring. If it doesn't, it's appended.
6412
     *
6413
     * @param string $str       <p>The input string.</p>
6414
     * @param string $substring <p>The substring to add if not present.</p>
6415
     *
6416
     * @psalm-pure
6417
     *
6418
     * @return string
6419
     */
6420 10
    public static function str_ensure_right(string $str, string $substring): string
6421
    {
6422
        if (
6423 10
            $str === ''
6424
            ||
6425 10
            $substring === ''
6426
            ||
6427 10
            \substr($str, -\strlen($substring)) !== $substring
6428
        ) {
6429 4
            $str .= $substring;
6430
        }
6431
6432 10
        return $str;
6433
    }
6434
6435
    /**
6436
     * Capitalizes the first word of the string, replaces underscores with
6437
     * spaces, and strips '_id'.
6438
     *
6439
     * @param string $str
6440
     *
6441
     * @psalm-pure
6442
     *
6443
     * @return string
6444
     */
6445 3
    public static function str_humanize($str): string
6446
    {
6447 3
        $str = \str_replace(
6448
            [
6449 3
                '_id',
6450
                '_',
6451
            ],
6452
            [
6453 3
                '',
6454
                ' ',
6455
            ],
6456 3
            $str
6457
        );
6458
6459 3
        return self::ucfirst(\trim($str));
6460
    }
6461
6462
    /**
6463
     * alias for "UTF8::str_istarts_with()"
6464
     *
6465
     * @param string $haystack
6466
     * @param string $needle
6467
     *
6468
     * @psalm-pure
6469
     *
6470
     * @return bool
6471
     *
6472
     * @see        UTF8::str_istarts_with()
6473
     * @deprecated <p>please use "UTF8::str_istarts_with()"</p>
6474
     */
6475 1
    public static function str_ibegins(string $haystack, string $needle): bool
6476
    {
6477 1
        return self::str_istarts_with($haystack, $needle);
6478
    }
6479
6480
    /**
6481
     * alias for "UTF8::str_iends_with()"
6482
     *
6483
     * @param string $haystack
6484
     * @param string $needle
6485
     *
6486
     * @psalm-pure
6487
     *
6488
     * @return bool
6489
     *
6490
     * @see        UTF8::str_iends_with()
6491
     * @deprecated <p>please use "UTF8::str_iends_with()"</p>
6492
     */
6493 1
    public static function str_iends(string $haystack, string $needle): bool
6494
    {
6495 1
        return self::str_iends_with($haystack, $needle);
6496
    }
6497
6498
    /**
6499
     * Check if the string ends with the given substring, case-insensitive.
6500
     *
6501
     * EXAMPLE: <code>
6502
     * UTF8::str_iends_with('BeginMiddleΚόσμε', 'Κόσμε'); // true
6503
     * UTF8::str_iends_with('BeginMiddleΚόσμε', 'κόσμε'); // true
6504
     * </code>
6505
     *
6506
     * @param string $haystack <p>The string to search in.</p>
6507
     * @param string $needle   <p>The substring to search for.</p>
6508
     *
6509
     * @psalm-pure
6510
     *
6511
     * @return bool
6512
     */
6513 12
    public static function str_iends_with(string $haystack, string $needle): bool
6514
    {
6515 12
        if ($needle === '') {
6516 2
            return true;
6517
        }
6518
6519 12
        if ($haystack === '') {
6520
            return false;
6521
        }
6522
6523 12
        return self::strcasecmp(\substr($haystack, -\strlen($needle)), $needle) === 0;
6524
    }
6525
6526
    /**
6527
     * Returns true if the string ends with any of $substrings, false otherwise.
6528
     *
6529
     * - case-insensitive
6530
     *
6531
     * @param string   $str        <p>The input string.</p>
6532
     * @param string[] $substrings <p>Substrings to look for.</p>
6533
     *
6534
     * @psalm-pure
6535
     *
6536
     * @return bool
6537
     *              <p>Whether or not $str ends with $substring.</p>
6538
     */
6539 4
    public static function str_iends_with_any(string $str, array $substrings): bool
6540
    {
6541 4
        if ($substrings === []) {
6542
            return false;
6543
        }
6544
6545 4
        foreach ($substrings as &$substring) {
6546 4
            if (self::str_iends_with($str, $substring)) {
6547 4
                return true;
6548
            }
6549
        }
6550
6551
        return false;
6552
    }
6553
6554
    /**
6555
     * Returns the index of the first occurrence of $needle in the string,
6556
     * and false if not found. Accepts an optional offset from which to begin
6557
     * the search.
6558
     *
6559
     * @param string $str      <p>The input string.</p>
6560
     * @param string $needle   <p>Substring to look for.</p>
6561
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
6562
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6563
     *
6564
     * @psalm-pure
6565
     *
6566
     * @return false|int
6567
     *                   <p>The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
6568
     *
6569
     * @see        UTF8::stripos()
6570
     * @deprecated <p>please use "UTF8::stripos()"</p>
6571
     */
6572 1
    public static function str_iindex_first(
6573
        string $str,
6574
        string $needle,
6575
        int $offset = 0,
6576
        string $encoding = 'UTF-8'
6577
    ) {
6578 1
        return self::stripos(
6579 1
            $str,
6580 1
            $needle,
6581 1
            $offset,
6582 1
            $encoding
6583
        );
6584
    }
6585
6586
    /**
6587
     * Returns the index of the last occurrence of $needle in the string,
6588
     * and false if not found. Accepts an optional offset from which to begin
6589
     * the search. Offsets may be negative to count from the last character
6590
     * in the string.
6591
     *
6592
     * @param string $str      <p>The input string.</p>
6593
     * @param string $needle   <p>Substring to look for.</p>
6594
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
6595
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6596
     *
6597
     * @psalm-pure
6598
     *
6599
     * @return false|int
6600
     *                   <p>The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
6601
     *
6602
     * @see        UTF8::strripos()
6603
     * @deprecated <p>please use "UTF8::strripos()"</p>
6604
     */
6605 10
    public static function str_iindex_last(
6606
        string $str,
6607
        string $needle,
6608
        int $offset = 0,
6609
        string $encoding = 'UTF-8'
6610
    ) {
6611 10
        return self::strripos(
6612 10
            $str,
6613 10
            $needle,
6614 10
            $offset,
6615 10
            $encoding
6616
        );
6617
    }
6618
6619
    /**
6620
     * Returns the index of the first occurrence of $needle in the string,
6621
     * and false if not found. Accepts an optional offset from which to begin
6622
     * the search.
6623
     *
6624
     * @param string $str      <p>The input string.</p>
6625
     * @param string $needle   <p>Substring to look for.</p>
6626
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
6627
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6628
     *
6629
     * @psalm-pure
6630
     *
6631
     * @return false|int
6632
     *                   <p>The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
6633
     *
6634
     * @see        UTF8::strpos()
6635
     * @deprecated <p>please use "UTF8::strpos()"</p>
6636
     */
6637 11
    public static function str_index_first(
6638
        string $str,
6639
        string $needle,
6640
        int $offset = 0,
6641
        string $encoding = 'UTF-8'
6642
    ) {
6643 11
        return self::strpos(
6644 11
            $str,
6645 11
            $needle,
6646 11
            $offset,
6647 11
            $encoding
6648
        );
6649
    }
6650
6651
    /**
6652
     * Returns the index of the last occurrence of $needle in the string,
6653
     * and false if not found. Accepts an optional offset from which to begin
6654
     * the search. Offsets may be negative to count from the last character
6655
     * in the string.
6656
     *
6657
     * @param string $str      <p>The input string.</p>
6658
     * @param string $needle   <p>Substring to look for.</p>
6659
     * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
6660
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6661
     *
6662
     * @psalm-pure
6663
     *
6664
     * @return false|int
6665
     *                   <p>The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
6666
     *
6667
     * @see        UTF8::strrpos()
6668
     * @deprecated <p>please use "UTF8::strrpos()"</p>
6669
     */
6670 10
    public static function str_index_last(
6671
        string $str,
6672
        string $needle,
6673
        int $offset = 0,
6674
        string $encoding = 'UTF-8'
6675
    ) {
6676 10
        return self::strrpos(
6677 10
            $str,
6678 10
            $needle,
6679 10
            $offset,
6680 10
            $encoding
6681
        );
6682
    }
6683
6684
    /**
6685
     * Inserts $substring into the string at the $index provided.
6686
     *
6687
     * @param string $str       <p>The input string.</p>
6688
     * @param string $substring <p>String to be inserted.</p>
6689
     * @param int    $index     <p>The index at which to insert the substring.</p>
6690
     * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
6691
     *
6692
     * @psalm-pure
6693
     *
6694
     * @return string
6695
     */
6696 8
    public static function str_insert(
6697
        string $str,
6698
        string $substring,
6699
        int $index,
6700
        string $encoding = 'UTF-8'
6701
    ): string {
6702 8
        if ($encoding === 'UTF-8') {
6703 4
            $len = (int) \mb_strlen($str);
6704 4
            if ($index > $len) {
6705
                return $str;
6706
            }
6707
6708
            /** @noinspection UnnecessaryCastingInspection */
6709 4
            return (string) \mb_substr($str, 0, $index) .
6710 4
                   $substring .
6711 4
                   (string) \mb_substr($str, $index, $len);
6712
        }
6713
6714 4
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
6715
6716 4
        $len = (int) self::strlen($str, $encoding);
6717 4
        if ($index > $len) {
6718 1
            return $str;
6719
        }
6720
6721 3
        return ((string) self::substr($str, 0, $index, $encoding)) .
6722 3
               $substring .
6723 3
               ((string) self::substr($str, $index, $len, $encoding));
6724
    }
6725
6726
    /**
6727
     * Case-insensitive and UTF-8 safe version of <function>str_replace</function>.
6728
     *
6729
     * EXAMPLE: <code>
6730
     * UTF8::str_ireplace('lIzÆ', 'lise', 'Iñtërnâtiônàlizætiøn'); // 'Iñtërnâtiônàlisetiøn'
6731
     * </code>
6732
     *
6733
     * @see http://php.net/manual/en/function.str-ireplace.php
6734
     *
6735
     * @param string|string[] $search      <p>
6736
     *                                     Every replacement with search array is
6737
     *                                     performed on the result of previous replacement.
6738
     *                                     </p>
6739
     * @param string|string[] $replacement <p>The replacement.</p>
6740
     * @param string|string[] $subject     <p>
6741
     *                                     If subject is an array, then the search and
6742
     *                                     replace is performed with every entry of
6743
     *                                     subject, and the return value is an array as
6744
     *                                     well.
6745
     *                                     </p>
6746
     * @param int             $count       [optional] <p>
6747
     *                                     The number of matched and replaced needles will
6748
     *                                     be returned in count which is passed by
6749
     *                                     reference.
6750
     *                                     </p>
6751
     *
6752
     * @psalm-pure
6753
     *
6754
     * @return string|string[]
6755
     *                         <p>A string or an array of replacements.</p>
6756
     *
6757
     * @template TStrIReplaceSubject
6758
     * @phpstan-param TStrIReplaceSubject $subject
6759
     * @phpstan-return TStrIReplaceSubject
6760
     */
6761 29
    public static function str_ireplace($search, $replacement, $subject, &$count = null)
6762
    {
6763 29
        $search = (array) $search;
6764
6765
        /** @noinspection AlterInForeachInspection */
6766 29
        foreach ($search as &$s) {
6767 29
            $s = (string) $s;
6768 29
            if ($s === '') {
6769 6
                $s = '/^(?<=.)$/';
6770
            } else {
6771 29
                $s = '/' . \preg_quote($s, '/') . '/ui';
6772
            }
6773
        }
6774
6775
        // fallback
6776
        /** @phpstan-ignore-next-line - only a fallback for PHP8 */
6777 29
        if ($replacement === null) {
0 ignored issues
show
introduced by
The condition $replacement === null is always false.
Loading history...
6778 1
            $replacement = '';
6779
        }
6780
        /** @phpstan-ignore-next-line - only a fallback for PHP8 */
6781 29
        if ($subject === null) {
6782 1
            $subject = '';
6783
        }
6784
6785
        /**
6786
         * @psalm-suppress PossiblyNullArgument
6787
         * @phpstan-var TStrIReplaceSubject $subject
6788
         */
6789 29
        $subject = \preg_replace($search, $replacement, $subject, -1, $count);
6790
6791 29
        return $subject;
6792
    }
6793
6794
    /**
6795
     * Replaces $search from the beginning of string with $replacement.
6796
     *
6797
     * @param string $str         <p>The input string.</p>
6798
     * @param string $search      <p>The string to search for.</p>
6799
     * @param string $replacement <p>The replacement.</p>
6800
     *
6801
     * @psalm-pure
6802
     *
6803
     * @return string
6804
     *                <p>The string after the replacement.</p>
6805
     */
6806 17
    public static function str_ireplace_beginning(string $str, string $search, string $replacement): string
6807
    {
6808 17
        if ($str === '') {
6809 4
            if ($replacement === '') {
6810 2
                return '';
6811
            }
6812
6813 2
            if ($search === '') {
6814 2
                return $replacement;
6815
            }
6816
        }
6817
6818 13
        if ($search === '') {
6819 2
            return $str . $replacement;
6820
        }
6821
6822 11
        $searchLength = \strlen($search);
6823 11
        if (\strncasecmp($str, $search, $searchLength) === 0) {
6824 10
            return $replacement . \substr($str, $searchLength);
6825
        }
6826
6827 1
        return $str;
6828
    }
6829
6830
    /**
6831
     * Replaces $search from the ending of string with $replacement.
6832
     *
6833
     * @param string $str         <p>The input string.</p>
6834
     * @param string $search      <p>The string to search for.</p>
6835
     * @param string $replacement <p>The replacement.</p>
6836
     *
6837
     * @psalm-pure
6838
     *
6839
     * @return string
6840
     *                <p>The string after the replacement.</p>
6841
     */
6842 17
    public static function str_ireplace_ending(string $str, string $search, string $replacement): string
6843
    {
6844 17
        if ($str === '') {
6845 4
            if ($replacement === '') {
6846 2
                return '';
6847
            }
6848
6849 2
            if ($search === '') {
6850 2
                return $replacement;
6851
            }
6852
        }
6853
6854 13
        if ($search === '') {
6855 2
            return $str . $replacement;
6856
        }
6857
6858 11
        if (\stripos($str, $search, \strlen($str) - \strlen($search)) !== false) {
6859 9
            $str = \substr($str, 0, -\strlen($search)) . $replacement;
6860
        }
6861
6862 11
        return $str;
6863
    }
6864
6865
    /**
6866
     * Check if the string starts with the given substring, case-insensitive.
6867
     *
6868
     * EXAMPLE: <code>
6869
     * UTF8::str_istarts_with('ΚόσμεMiddleEnd', 'Κόσμε'); // true
6870
     * UTF8::str_istarts_with('ΚόσμεMiddleEnd', 'κόσμε'); // true
6871
     * </code>
6872
     *
6873
     * @param string $haystack <p>The string to search in.</p>
6874
     * @param string $needle   <p>The substring to search for.</p>
6875
     *
6876
     * @psalm-pure
6877
     *
6878
     * @return bool
6879
     */
6880 13
    public static function str_istarts_with(string $haystack, string $needle): bool
6881
    {
6882 13
        if ($needle === '') {
6883 2
            return true;
6884
        }
6885
6886 13
        if ($haystack === '') {
6887
            return false;
6888
        }
6889
6890 13
        return self::stripos($haystack, $needle) === 0;
6891
    }
6892
6893
    /**
6894
     * Returns true if the string begins with any of $substrings, false otherwise.
6895
     *
6896
     * - case-insensitive
6897
     *
6898
     * @param string $str        <p>The input string.</p>
6899
     * @param array  $substrings <p>Substrings to look for.</p>
6900
     *
6901
     * @psalm-pure
6902
     *
6903
     * @return bool
6904
     *              <p>Whether or not $str starts with $substring.</p>
6905
     */
6906 5
    public static function str_istarts_with_any(string $str, array $substrings): bool
6907
    {
6908 5
        if ($str === '') {
6909
            return false;
6910
        }
6911
6912 5
        if ($substrings === []) {
6913
            return false;
6914
        }
6915
6916 5
        foreach ($substrings as &$substring) {
6917 5
            if (self::str_istarts_with($str, $substring)) {
6918 5
                return true;
6919
            }
6920
        }
6921
6922 1
        return false;
6923
    }
6924
6925
    /**
6926
     * Gets the substring after the first occurrence of a separator.
6927
     *
6928
     * @param string $str       <p>The input string.</p>
6929
     * @param string $separator <p>The string separator.</p>
6930
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
6931
     *
6932
     * @psalm-pure
6933
     *
6934
     * @return string
6935
     */
6936 1
    public static function str_isubstr_after_first_separator(
6937
        string $str,
6938
        string $separator,
6939
        string $encoding = 'UTF-8'
6940
    ): string {
6941 1
        if ($separator === '' || $str === '') {
6942 1
            return '';
6943
        }
6944
6945 1
        $offset = self::stripos($str, $separator);
6946 1
        if ($offset === false) {
6947 1
            return '';
6948
        }
6949
6950 1
        if ($encoding === 'UTF-8') {
6951 1
            return (string) \mb_substr(
6952 1
                $str,
6953 1
                $offset + (int) \mb_strlen($separator)
6954
            );
6955
        }
6956
6957
        return (string) self::substr(
6958
            $str,
6959
            $offset + (int) self::strlen($separator, $encoding),
6960
            null,
6961
            $encoding
6962
        );
6963
    }
6964
6965
    /**
6966
     * Gets the substring after the last occurrence of a separator.
6967
     *
6968
     * @param string $str       <p>The input string.</p>
6969
     * @param string $separator <p>The string separator.</p>
6970
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
6971
     *
6972
     * @psalm-pure
6973
     *
6974
     * @return string
6975
     */
6976 1
    public static function str_isubstr_after_last_separator(
6977
        string $str,
6978
        string $separator,
6979
        string $encoding = 'UTF-8'
6980
    ): string {
6981 1
        if ($separator === '' || $str === '') {
6982 1
            return '';
6983
        }
6984
6985 1
        $offset = self::strripos($str, $separator);
6986 1
        if ($offset === false) {
6987 1
            return '';
6988
        }
6989
6990 1
        if ($encoding === 'UTF-8') {
6991 1
            return (string) \mb_substr(
6992 1
                $str,
6993 1
                $offset + (int) self::strlen($separator)
6994
            );
6995
        }
6996
6997
        return (string) self::substr(
6998
            $str,
6999
            $offset + (int) self::strlen($separator, $encoding),
7000
            null,
7001
            $encoding
7002
        );
7003
    }
7004
7005
    /**
7006
     * Gets the substring before the first occurrence of a separator.
7007
     *
7008
     * @param string $str       <p>The input string.</p>
7009
     * @param string $separator <p>The string separator.</p>
7010
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
7011
     *
7012
     * @psalm-pure
7013
     *
7014
     * @return string
7015
     */
7016 1
    public static function str_isubstr_before_first_separator(
7017
        string $str,
7018
        string $separator,
7019
        string $encoding = 'UTF-8'
7020
    ): string {
7021 1
        if ($separator === '' || $str === '') {
7022 1
            return '';
7023
        }
7024
7025 1
        $offset = self::stripos($str, $separator);
7026 1
        if ($offset === false) {
7027 1
            return '';
7028
        }
7029
7030 1
        if ($encoding === 'UTF-8') {
7031 1
            return (string) \mb_substr($str, 0, $offset);
7032
        }
7033
7034
        return (string) self::substr($str, 0, $offset, $encoding);
7035
    }
7036
7037
    /**
7038
     * Gets the substring before the last occurrence of a separator.
7039
     *
7040
     * @param string $str       <p>The input string.</p>
7041
     * @param string $separator <p>The string separator.</p>
7042
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
7043
     *
7044
     * @psalm-pure
7045
     *
7046
     * @return string
7047
     */
7048 1
    public static function str_isubstr_before_last_separator(
7049
        string $str,
7050
        string $separator,
7051
        string $encoding = 'UTF-8'
7052
    ): string {
7053 1
        if ($separator === '' || $str === '') {
7054 1
            return '';
7055
        }
7056
7057 1
        if ($encoding === 'UTF-8') {
7058 1
            $offset = \mb_strripos($str, $separator);
7059 1
            if ($offset === false) {
7060 1
                return '';
7061
            }
7062
7063 1
            return (string) \mb_substr($str, 0, $offset);
7064
        }
7065
7066
        $offset = self::strripos($str, $separator, 0, $encoding);
7067
        if ($offset === false) {
7068
            return '';
7069
        }
7070
7071
        return (string) self::substr($str, 0, $offset, $encoding);
7072
    }
7073
7074
    /**
7075
     * Gets the substring after (or before via "$before_needle") the first occurrence of the "$needle".
7076
     *
7077
     * @param string $str           <p>The input string.</p>
7078
     * @param string $needle        <p>The string to look for.</p>
7079
     * @param bool   $before_needle [optional] <p>Default: false</p>
7080
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
7081
     *
7082
     * @psalm-pure
7083
     *
7084
     * @return string
7085
     */
7086 2
    public static function str_isubstr_first(
7087
        string $str,
7088
        string $needle,
7089
        bool $before_needle = false,
7090
        string $encoding = 'UTF-8'
7091
    ): string {
7092
        if (
7093 2
            $needle === ''
7094
            ||
7095 2
            $str === ''
7096
        ) {
7097 2
            return '';
7098
        }
7099
7100 2
        $part = self::stristr(
7101 2
            $str,
7102 2
            $needle,
7103 2
            $before_needle,
7104 2
            $encoding
7105
        );
7106 2
        if ($part === false) {
7107 2
            return '';
7108
        }
7109
7110 2
        return $part;
7111
    }
7112
7113
    /**
7114
     * Gets the substring after (or before via "$before_needle") the last occurrence of the "$needle".
7115
     *
7116
     * @param string $str           <p>The input string.</p>
7117
     * @param string $needle        <p>The string to look for.</p>
7118
     * @param bool   $before_needle [optional] <p>Default: false</p>
7119
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
7120
     *
7121
     * @psalm-pure
7122
     *
7123
     * @return string
7124
     */
7125 1
    public static function str_isubstr_last(
7126
        string $str,
7127
        string $needle,
7128
        bool $before_needle = false,
7129
        string $encoding = 'UTF-8'
7130
    ): string {
7131
        if (
7132 1
            $needle === ''
7133
            ||
7134 1
            $str === ''
7135
        ) {
7136 1
            return '';
7137
        }
7138
7139 1
        $part = self::strrichr(
7140 1
            $str,
7141 1
            $needle,
7142 1
            $before_needle,
7143 1
            $encoding
7144
        );
7145 1
        if ($part === false) {
7146 1
            return '';
7147
        }
7148
7149 1
        return $part;
7150
    }
7151
7152
    /**
7153
     * Returns the last $n characters of the string.
7154
     *
7155
     * @param string $str      <p>The input string.</p>
7156
     * @param int    $n        <p>Number of characters to retrieve from the end.</p>
7157
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7158
     *
7159
     * @psalm-pure
7160
     *
7161
     * @return string
7162
     */
7163 12
    public static function str_last_char(
7164
        string $str,
7165
        int $n = 1,
7166
        string $encoding = 'UTF-8'
7167
    ): string {
7168 12
        if ($str === '' || $n <= 0) {
7169 4
            return '';
7170
        }
7171
7172 8
        if ($encoding === 'UTF-8') {
7173 4
            return (string) \mb_substr($str, -$n);
7174
        }
7175
7176 4
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
7177
7178 4
        return (string) self::substr($str, -$n, null, $encoding);
7179
    }
7180
7181
    /**
7182
     * Limit the number of characters in a string.
7183
     *
7184
     * @param string $str        <p>The input string.</p>
7185
     * @param int    $length     [optional] <p>Default: 100</p>
7186
     * @param string $str_add_on [optional] <p>Default: …</p>
7187
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
7188
     *
7189
     * @psalm-pure
7190
     *
7191
     * @return string
7192
     */
7193 2
    public static function str_limit(
7194
        string $str,
7195
        int $length = 100,
7196
        string $str_add_on = '…',
7197
        string $encoding = 'UTF-8'
7198
    ): string {
7199 2
        if ($str === '' || $length <= 0) {
7200 2
            return '';
7201
        }
7202
7203 2
        if ($encoding === 'UTF-8') {
7204 2
            if ((int) \mb_strlen($str) <= $length) {
7205 2
                return $str;
7206
            }
7207
7208
            /** @noinspection UnnecessaryCastingInspection */
7209 2
            return (string) \mb_substr($str, 0, $length - (int) self::strlen($str_add_on)) . $str_add_on;
7210
        }
7211
7212
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
7213
7214
        if ((int) self::strlen($str, $encoding) <= $length) {
7215
            return $str;
7216
        }
7217
7218
        return ((string) self::substr($str, 0, $length - (int) self::strlen($str_add_on), $encoding)) . $str_add_on;
7219
    }
7220
7221
    /**
7222
     * Limit the number of characters in a string, but also after the next word.
7223
     *
7224
     * EXAMPLE: <code>UTF8::str_limit_after_word('fòô bàř fòô', 8, ''); // 'fòô bàř'</code>
7225
     *
7226
     * @param string $str        <p>The input string.</p>
7227
     * @param int    $length     [optional] <p>Default: 100</p>
7228
     * @param string $str_add_on [optional] <p>Default: …</p>
7229
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
7230
     *
7231
     * @psalm-pure
7232
     *
7233
     * @return string
7234
     */
7235 6
    public static function str_limit_after_word(
7236
        string $str,
7237
        int $length = 100,
7238
        string $str_add_on = '…',
7239
        string $encoding = 'UTF-8'
7240
    ): string {
7241 6
        if ($str === '' || $length <= 0) {
7242 2
            return '';
7243
        }
7244
7245 6
        if ($encoding === 'UTF-8') {
7246
            /** @noinspection UnnecessaryCastingInspection */
7247 2
            if ((int) \mb_strlen($str) <= $length) {
7248 2
                return $str;
7249
            }
7250
7251 2
            if (\mb_substr($str, $length - 1, 1) === ' ') {
7252 2
                return ((string) \mb_substr($str, 0, $length - 1)) . $str_add_on;
7253
            }
7254
7255 2
            $str = \mb_substr($str, 0, $length);
7256
7257 2
            $array = \explode(' ', $str, -1);
7258 2
            $new_str = \implode(' ', $array);
7259
7260 2
            if ($new_str === '') {
7261 2
                return ((string) \mb_substr($str, 0, $length - 1)) . $str_add_on;
7262
            }
7263
        } else {
7264 4
            if ((int) self::strlen($str, $encoding) <= $length) {
7265
                return $str;
7266
            }
7267
7268 4
            if (self::substr($str, $length - 1, 1, $encoding) === ' ') {
7269 3
                return ((string) self::substr($str, 0, $length - 1, $encoding)) . $str_add_on;
7270
            }
7271
7272
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
7273 1
            $str = self::substr($str, 0, $length, $encoding);
7274
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
7275 1
            if ($str === false) {
7276
                return '' . $str_add_on;
7277
            }
7278
7279 1
            $array = \explode(' ', $str, -1);
7280 1
            $new_str = \implode(' ', $array);
7281
7282 1
            if ($new_str === '') {
7283
                return ((string) self::substr($str, 0, $length - 1, $encoding)) . $str_add_on;
7284
            }
7285
        }
7286
7287 3
        return $new_str . $str_add_on;
7288
    }
7289
7290
    /**
7291
     * Returns the longest common prefix between the $str1 and $str2.
7292
     *
7293
     * @param string $str1     <p>The input sting.</p>
7294
     * @param string $str2     <p>Second string for comparison.</p>
7295
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7296
     *
7297
     * @psalm-pure
7298
     *
7299
     * @return string
7300
     */
7301 10
    public static function str_longest_common_prefix(
7302
        string $str1,
7303
        string $str2,
7304
        string $encoding = 'UTF-8'
7305
    ): string {
7306
        // init
7307 10
        $longest_common_prefix = '';
7308
7309 10
        if ($encoding === 'UTF-8') {
7310 5
            $max_length = (int) \min(
7311 5
                \mb_strlen($str1),
7312 5
                \mb_strlen($str2)
7313
            );
7314
7315 5
            for ($i = 0; $i < $max_length; ++$i) {
7316 4
                $char = \mb_substr($str1, $i, 1);
7317
7318
                if (
7319 4
                    $char !== false
7320
                    &&
7321 4
                    $char === \mb_substr($str2, $i, 1)
7322
                ) {
7323 3
                    $longest_common_prefix .= $char;
7324
                } else {
7325 3
                    break;
7326
                }
7327
            }
7328
        } else {
7329 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
7330
7331 5
            $max_length = (int) \min(
7332 5
                self::strlen($str1, $encoding),
7333 5
                self::strlen($str2, $encoding)
7334
            );
7335
7336 5
            for ($i = 0; $i < $max_length; ++$i) {
7337 4
                $char = self::substr($str1, $i, 1, $encoding);
7338
7339
                if (
7340 4
                    $char !== false
7341
                    &&
7342 4
                    $char === self::substr($str2, $i, 1, $encoding)
7343
                ) {
7344 3
                    $longest_common_prefix .= $char;
7345
                } else {
7346 3
                    break;
7347
                }
7348
            }
7349
        }
7350
7351 10
        return $longest_common_prefix;
7352
    }
7353
7354
    /**
7355
     * Returns the longest common substring between the $str1 and $str2.
7356
     * In the case of ties, it returns that which occurs first.
7357
     *
7358
     * @param string $str1
7359
     * @param string $str2     <p>Second string for comparison.</p>
7360
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7361
     *
7362
     * @psalm-pure
7363
     *
7364
     * @return string
7365
     *                <p>A string with its $str being the longest common substring.</p>
7366
     */
7367 11
    public static function str_longest_common_substring(
7368
        string $str1,
7369
        string $str2,
7370
        string $encoding = 'UTF-8'
7371
    ): string {
7372 11
        if ($str1 === '' || $str2 === '') {
7373 2
            return '';
7374
        }
7375
7376
        // Uses dynamic programming to solve
7377
        // http://en.wikipedia.org/wiki/Longest_common_substring_problem
7378
7379 9
        if ($encoding === 'UTF-8') {
7380 4
            $str_length = (int) \mb_strlen($str1);
7381 4
            $other_length = (int) \mb_strlen($str2);
7382
        } else {
7383 5
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
7384
7385 5
            $str_length = (int) self::strlen($str1, $encoding);
7386 5
            $other_length = (int) self::strlen($str2, $encoding);
7387
        }
7388
7389
        // Return if either string is empty
7390 9
        if ($str_length === 0 || $other_length === 0) {
7391
            return '';
7392
        }
7393
7394 9
        $len = 0;
7395 9
        $end = 0;
7396 9
        $table = \array_fill(
7397 9
            0,
7398 9
            $str_length + 1,
7399 9
            \array_fill(0, $other_length + 1, 0)
7400
        );
7401
7402 9
        if ($encoding === 'UTF-8') {
7403 9
            for ($i = 1; $i <= $str_length; ++$i) {
7404 9
                for ($j = 1; $j <= $other_length; ++$j) {
7405 9
                    $str_char = \mb_substr($str1, $i - 1, 1);
7406 9
                    $other_char = \mb_substr($str2, $j - 1, 1);
7407
7408 9
                    if ($str_char === $other_char) {
7409 8
                        $table[$i][$j] = $table[$i - 1][$j - 1] + 1;
7410 8
                        if ($table[$i][$j] > $len) {
7411 8
                            $len = $table[$i][$j];
7412 8
                            $end = $i;
7413
                        }
7414
                    } else {
7415 9
                        $table[$i][$j] = 0;
7416
                    }
7417
                }
7418
            }
7419
        } else {
7420
            for ($i = 1; $i <= $str_length; ++$i) {
7421
                for ($j = 1; $j <= $other_length; ++$j) {
7422
                    $str_char = self::substr($str1, $i - 1, 1, $encoding);
7423
                    $other_char = self::substr($str2, $j - 1, 1, $encoding);
7424
7425
                    if ($str_char === $other_char) {
7426
                        $table[$i][$j] = $table[$i - 1][$j - 1] + 1;
7427
                        if ($table[$i][$j] > $len) {
7428
                            $len = $table[$i][$j];
7429
                            $end = $i;
7430
                        }
7431
                    } else {
7432
                        $table[$i][$j] = 0;
7433
                    }
7434
                }
7435
            }
7436
        }
7437
7438 9
        if ($encoding === 'UTF-8') {
7439 9
            return (string) \mb_substr($str1, $end - $len, $len);
7440
        }
7441
7442
        return (string) self::substr($str1, $end - $len, $len, $encoding);
7443
    }
7444
7445
    /**
7446
     * Returns the longest common suffix between the $str1 and $str2.
7447
     *
7448
     * @param string $str1
7449
     * @param string $str2     <p>Second string for comparison.</p>
7450
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7451
     *
7452
     * @psalm-pure
7453
     *
7454
     * @return string
7455
     */
7456 10
    public static function str_longest_common_suffix(
7457
        string $str1,
7458
        string $str2,
7459
        string $encoding = 'UTF-8'
7460
    ): string {
7461 10
        if ($str1 === '' || $str2 === '') {
7462 2
            return '';
7463
        }
7464
7465 8
        if ($encoding === 'UTF-8') {
7466 4
            $max_length = (int) \min(
7467 4
                \mb_strlen($str1, $encoding),
7468 4
                \mb_strlen($str2, $encoding)
7469
            );
7470
7471 4
            $longest_common_suffix = '';
7472 4
            for ($i = 1; $i <= $max_length; ++$i) {
7473 4
                $char = \mb_substr($str1, -$i, 1);
7474
7475
                if (
7476 4
                    $char !== false
7477
                    &&
7478 4
                    $char === \mb_substr($str2, -$i, 1)
7479
                ) {
7480 3
                    $longest_common_suffix = $char . $longest_common_suffix;
7481
                } else {
7482 3
                    break;
7483
                }
7484
            }
7485
        } else {
7486 4
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
7487
7488 4
            $max_length = (int) \min(
7489 4
                self::strlen($str1, $encoding),
7490 4
                self::strlen($str2, $encoding)
7491
            );
7492
7493 4
            $longest_common_suffix = '';
7494 4
            for ($i = 1; $i <= $max_length; ++$i) {
7495 4
                $char = self::substr($str1, -$i, 1, $encoding);
7496
7497
                if (
7498 4
                    $char !== false
7499
                    &&
7500 4
                    $char === self::substr($str2, -$i, 1, $encoding)
7501
                ) {
7502 3
                    $longest_common_suffix = $char . $longest_common_suffix;
7503
                } else {
7504 3
                    break;
7505
                }
7506
            }
7507
        }
7508
7509 8
        return $longest_common_suffix;
7510
    }
7511
7512
    /**
7513
     * Returns true if $str matches the supplied pattern, false otherwise.
7514
     *
7515
     * @param string $str     <p>The input string.</p>
7516
     * @param string $pattern <p>Regex pattern to match against.</p>
7517
     *
7518
     * @psalm-pure
7519
     *
7520
     * @return bool
7521
     *              <p>Whether or not $str matches the pattern.</p>
7522
     */
7523 10
    public static function str_matches_pattern(string $str, string $pattern): bool
7524
    {
7525 10
        return (bool) \preg_match('/' . $pattern . '/u', $str);
7526
    }
7527
7528
    /**
7529
     * Returns whether or not a character exists at an index. Offsets may be
7530
     * negative to count from the last character in the string. Implements
7531
     * part of the ArrayAccess interface.
7532
     *
7533
     * @param string $str      <p>The input string.</p>
7534
     * @param int    $offset   <p>The index to check.</p>
7535
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7536
     *
7537
     * @psalm-pure
7538
     *
7539
     * @return bool
7540
     *              <p>Whether or not the index exists.</p>
7541
     */
7542 6
    public static function str_offset_exists(string $str, int $offset, string $encoding = 'UTF-8'): bool
7543
    {
7544
        // init
7545 6
        $length = (int) self::strlen($str, $encoding);
7546
7547 6
        if ($offset >= 0) {
7548 3
            return $length > $offset;
7549
        }
7550
7551 3
        return $length >= \abs($offset);
7552
    }
7553
7554
    /**
7555
     * Returns the character at the given index. Offsets may be negative to
7556
     * count from the last character in the string. Implements part of the
7557
     * ArrayAccess interface, and throws an OutOfBoundsException if the index
7558
     * does not exist.
7559
     *
7560
     * @param string $str      <p>The input string.</p>
7561
     * @param int    $index    <p>The <strong>index</strong> from which to retrieve the char.</p>
7562
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7563
     *
7564
     * @throws \OutOfBoundsException if the positive or negative offset does not exist
7565
     *
7566
     * @return string
7567
     *                <p>The character at the specified index.</p>
7568
     *
7569
     * @psalm-pure
7570
     */
7571 2
    public static function str_offset_get(string $str, int $index, string $encoding = 'UTF-8'): string
7572
    {
7573
        // init
7574 2
        $length = (int) self::strlen($str);
7575
7576
        if (
7577 2
            ($index >= 0 && $length <= $index)
7578
            ||
7579 2
            $length < \abs($index)
7580
        ) {
7581 1
            throw new \OutOfBoundsException('No character exists at the index');
7582
        }
7583
7584 1
        return self::char_at($str, $index, $encoding);
7585
    }
7586
7587
    /**
7588
     * Pad a UTF-8 string to a given length with another string.
7589
     *
7590
     * EXAMPLE: <code>UTF8::str_pad('中文空白', 10, '_', STR_PAD_BOTH); // '___中文空白___'</code>
7591
     *
7592
     * @param string     $str        <p>The input string.</p>
7593
     * @param int        $pad_length <p>The length of return string.</p>
7594
     * @param string     $pad_string [optional] <p>String to use for padding the input string.</p>
7595
     * @param int|string $pad_type   [optional] <p>
7596
     *                               Can be <strong>STR_PAD_RIGHT</strong> (default), [or string "right"]<br>
7597
     *                               <strong>STR_PAD_LEFT</strong> [or string "left"] or<br>
7598
     *                               <strong>STR_PAD_BOTH</strong> [or string "both"]
7599
     *                               </p>
7600
     * @param string     $encoding   [optional] <p>Default: 'UTF-8'</p>
7601
     *
7602
     * @psalm-pure
7603
     *
7604
     * @return string
7605
     *                <p>Returns the padded string.</p>
7606
     */
7607 41
    public static function str_pad(
7608
        string $str,
7609
        int $pad_length,
7610
        string $pad_string = ' ',
7611
        $pad_type = \STR_PAD_RIGHT,
7612
        string $encoding = 'UTF-8'
7613
    ): string {
7614 41
        if ($pad_length === 0 || $pad_string === '') {
7615 1
            return $str;
7616
        }
7617
7618 41
        if ($pad_type !== (int) $pad_type) {
7619 13
            if ($pad_type === 'left') {
7620 3
                $pad_type = \STR_PAD_LEFT;
7621 10
            } elseif ($pad_type === 'right') {
7622 6
                $pad_type = \STR_PAD_RIGHT;
7623 4
            } elseif ($pad_type === 'both') {
7624 3
                $pad_type = \STR_PAD_BOTH;
7625
            } else {
7626 1
                throw new \InvalidArgumentException(
7627 1
                    'Pad expects $pad_type to be "STR_PAD_*" or ' . "to be one of 'left', 'right' or 'both'"
7628
                );
7629
            }
7630
        }
7631
7632 40
        if ($encoding === 'UTF-8') {
7633 25
            $str_length = (int) \mb_strlen($str);
7634
7635 25
            if ($pad_length >= $str_length) {
7636
                switch ($pad_type) {
7637 25
                    case \STR_PAD_LEFT:
7638 8
                        $ps_length = (int) \mb_strlen($pad_string);
7639
7640 8
                        $diff = ($pad_length - $str_length);
7641
7642 8
                        $pre = (string) \mb_substr(
7643 8
                            \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
7644 8
                            0,
7645 8
                            $diff
7646
                        );
7647 8
                        $post = '';
7648
7649 8
                        break;
7650
7651 20
                    case \STR_PAD_BOTH:
7652 14
                        $diff = ($pad_length - $str_length);
7653
7654 14
                        $ps_length_left = (int) \floor($diff / 2);
7655
7656 14
                        $ps_length_right = (int) \ceil($diff / 2);
7657
7658 14
                        $pre = (string) \mb_substr(
7659 14
                            \str_repeat($pad_string, $ps_length_left),
7660 14
                            0,
7661 14
                            $ps_length_left
7662
                        );
7663 14
                        $post = (string) \mb_substr(
7664 14
                            \str_repeat($pad_string, $ps_length_right),
7665 14
                            0,
7666 14
                            $ps_length_right
7667
                        );
7668
7669 14
                        break;
7670
7671 9
                    case \STR_PAD_RIGHT:
7672
                    default:
7673 9
                        $ps_length = (int) \mb_strlen($pad_string);
7674
7675 9
                        $diff = ($pad_length - $str_length);
7676
7677 9
                        $post = (string) \mb_substr(
7678 9
                            \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
7679 9
                            0,
7680 9
                            $diff
7681
                        );
7682 9
                        $pre = '';
7683
                }
7684
7685 25
                return $pre . $str . $post;
7686
            }
7687
7688 3
            return $str;
7689
        }
7690
7691 15
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
7692
7693 15
        $str_length = (int) self::strlen($str, $encoding);
7694
7695 15
        if ($pad_length >= $str_length) {
7696
            switch ($pad_type) {
7697 14
                case \STR_PAD_LEFT:
7698 5
                    $ps_length = (int) self::strlen($pad_string, $encoding);
7699
7700 5
                    $diff = ($pad_length - $str_length);
7701
7702 5
                    $pre = (string) self::substr(
7703 5
                        \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
7704 5
                        0,
7705 5
                        $diff,
7706 5
                        $encoding
7707
                    );
7708 5
                    $post = '';
7709
7710 5
                    break;
7711
7712 9
                case \STR_PAD_BOTH:
7713 3
                    $diff = ($pad_length - $str_length);
7714
7715 3
                    $ps_length_left = (int) \floor($diff / 2);
7716
7717 3
                    $ps_length_right = (int) \ceil($diff / 2);
7718
7719 3
                    $pre = (string) self::substr(
7720 3
                        \str_repeat($pad_string, $ps_length_left),
7721 3
                        0,
7722 3
                        $ps_length_left,
7723 3
                        $encoding
7724
                    );
7725 3
                    $post = (string) self::substr(
7726 3
                        \str_repeat($pad_string, $ps_length_right),
7727 3
                        0,
7728 3
                        $ps_length_right,
7729 3
                        $encoding
7730
                    );
7731
7732 3
                    break;
7733
7734 6
                case \STR_PAD_RIGHT:
7735
                default:
7736 6
                    $ps_length = (int) self::strlen($pad_string, $encoding);
7737
7738 6
                    $diff = ($pad_length - $str_length);
7739
7740 6
                    $post = (string) self::substr(
7741 6
                        \str_repeat($pad_string, (int) \ceil($diff / $ps_length)),
7742 6
                        0,
7743 6
                        $diff,
7744 6
                        $encoding
7745
                    );
7746 6
                    $pre = '';
7747
            }
7748
7749 14
            return $pre . $str . $post;
7750
        }
7751
7752 1
        return $str;
7753
    }
7754
7755
    /**
7756
     * Returns a new string of a given length such that both sides of the
7757
     * string are padded. Alias for "UTF8::str_pad()" with a $pad_type of 'both'.
7758
     *
7759
     * @param string $str
7760
     * @param int    $length   <p>Desired string length after padding.</p>
7761
     * @param string $pad_str  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
7762
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7763
     *
7764
     * @psalm-pure
7765
     *
7766
     * @return string
7767
     *                <p>The string with padding applied.</p>
7768
     */
7769 11
    public static function str_pad_both(
7770
        string $str,
7771
        int $length,
7772
        string $pad_str = ' ',
7773
        string $encoding = 'UTF-8'
7774
    ): string {
7775 11
        return self::str_pad(
7776 11
            $str,
7777 11
            $length,
7778 11
            $pad_str,
7779 11
            \STR_PAD_BOTH,
7780 11
            $encoding
7781
        );
7782
    }
7783
7784
    /**
7785
     * Returns a new string of a given length such that the beginning of the
7786
     * string is padded. Alias for "UTF8::str_pad()" with a $pad_type of 'left'.
7787
     *
7788
     * @param string $str
7789
     * @param int    $length   <p>Desired string length after padding.</p>
7790
     * @param string $pad_str  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
7791
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7792
     *
7793
     * @psalm-pure
7794
     *
7795
     * @return string
7796
     *                <p>The string with left padding.</p>
7797
     */
7798 7
    public static function str_pad_left(
7799
        string $str,
7800
        int $length,
7801
        string $pad_str = ' ',
7802
        string $encoding = 'UTF-8'
7803
    ): string {
7804 7
        return self::str_pad(
7805 7
            $str,
7806 7
            $length,
7807 7
            $pad_str,
7808 7
            \STR_PAD_LEFT,
7809 7
            $encoding
7810
        );
7811
    }
7812
7813
    /**
7814
     * Returns a new string of a given length such that the end of the string
7815
     * is padded. Alias for "UTF8::str_pad()" with a $pad_type of 'right'.
7816
     *
7817
     * @param string $str
7818
     * @param int    $length   <p>Desired string length after padding.</p>
7819
     * @param string $pad_str  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
7820
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7821
     *
7822
     * @psalm-pure
7823
     *
7824
     * @return string
7825
     *                <p>The string with right padding.</p>
7826
     */
7827 7
    public static function str_pad_right(
7828
        string $str,
7829
        int $length,
7830
        string $pad_str = ' ',
7831
        string $encoding = 'UTF-8'
7832
    ): string {
7833 7
        return self::str_pad(
7834 7
            $str,
7835 7
            $length,
7836 7
            $pad_str,
7837 7
            \STR_PAD_RIGHT,
7838 7
            $encoding
7839
        );
7840
    }
7841
7842
    /**
7843
     * Repeat a string.
7844
     *
7845
     * EXAMPLE: <code>UTF8::str_repeat("°~\xf0\x90\x28\xbc", 2); // '°~ð(¼°~ð(¼'</code>
7846
     *
7847
     * @param string $str        <p>
7848
     *                           The string to be repeated.
7849
     *                           </p>
7850
     * @param int    $multiplier <p>
7851
     *                           Number of time the input string should be
7852
     *                           repeated.
7853
     *                           </p>
7854
     *                           <p>
7855
     *                           multiplier has to be greater than or equal to 0.
7856
     *                           If the multiplier is set to 0, the function
7857
     *                           will return an empty string.
7858
     *                           </p>
7859
     *
7860
     * @psalm-pure
7861
     *
7862
     * @return string
7863
     *                <p>The repeated string.</p>
7864
     */
7865 9
    public static function str_repeat(string $str, int $multiplier): string
7866
    {
7867 9
        $str = self::filter($str);
7868
7869 9
        return \str_repeat($str, $multiplier);
7870
    }
7871
7872
    /**
7873
     * INFO: This is only a wrapper for "str_replace()"  -> the original functions is already UTF-8 safe.
7874
     *
7875
     * Replace all occurrences of the search string with the replacement string
7876
     *
7877
     * @see http://php.net/manual/en/function.str-replace.php
7878
     *
7879
     * @param string|string[] $search  <p>
7880
     *                                 The value being searched for, otherwise known as the needle.
7881
     *                                 An array may be used to designate multiple needles.
7882
     *                                 </p>
7883
     * @param string|string[] $replace <p>
7884
     *                                 The replacement value that replaces found search
7885
     *                                 values. An array may be used to designate multiple replacements.
7886
     *                                 </p>
7887
     * @param string|string[] $subject <p>
7888
     *                                 The string or array of strings being searched and replaced on,
7889
     *                                 otherwise known as the haystack.
7890
     *                                 </p>
7891
     *                                 <p>
7892
     *                                 If subject is an array, then the search and
7893
     *                                 replace is performed with every entry of
7894
     *                                 subject, and the return value is an array as
7895
     *                                 well.
7896
     *                                 </p>
7897
     * @param int|null        $count   [optional] <p>
7898
     *                                 If passed, this will hold the number of matched and replaced needles.
7899
     *                                 </p>
7900
     *
7901
     * @psalm-pure
7902
     *
7903
     * @return string|string[]
7904
     *                         <p>This function returns a string or an array with the replaced values.</p>
7905
     *
7906
     * @template TStrReplaceSubject
7907
     * @phpstan-param TStrReplaceSubject $subject
7908
     * @phpstan-return TStrReplaceSubject
7909
     *
7910
     * @deprecated please use \str_replace() instead
7911
     */
7912 12
    public static function str_replace(
7913
        $search,
7914
        $replace,
7915
        $subject,
7916
        int &$count = null
7917
    ) {
7918
        /**
7919
         * @psalm-suppress PossiblyNullArgument
7920
         * @phpstan-var TStrReplaceSubject $return;
7921
         */
7922 12
        $return = \str_replace(
7923 12
            $search,
7924 12
            $replace,
7925 12
            $subject,
7926 12
            $count
7927
        );
7928
7929 12
        return $return;
7930
    }
7931
7932
    /**
7933
     * Replaces $search from the beginning of string with $replacement.
7934
     *
7935
     * @param string $str         <p>The input string.</p>
7936
     * @param string $search      <p>The string to search for.</p>
7937
     * @param string $replacement <p>The replacement.</p>
7938
     *
7939
     * @psalm-pure
7940
     *
7941
     * @return string
7942
     *                <p>A string after the replacements.</p>
7943
     */
7944 17
    public static function str_replace_beginning(
7945
        string $str,
7946
        string $search,
7947
        string $replacement
7948
    ): string {
7949 17
        if ($str === '') {
7950 4
            if ($replacement === '') {
7951 2
                return '';
7952
            }
7953
7954 2
            if ($search === '') {
7955 2
                return $replacement;
7956
            }
7957
        }
7958
7959 13
        if ($search === '') {
7960 2
            return $str . $replacement;
7961
        }
7962
7963 11
        $searchLength = \strlen($search);
7964 11
        if (\strncmp($str, $search, $searchLength) === 0) {
7965 9
            return $replacement . \substr($str, $searchLength);
7966
        }
7967
7968 2
        return $str;
7969
    }
7970
7971
    /**
7972
     * Replaces $search from the ending of string with $replacement.
7973
     *
7974
     * @param string $str         <p>The input string.</p>
7975
     * @param string $search      <p>The string to search for.</p>
7976
     * @param string $replacement <p>The replacement.</p>
7977
     *
7978
     * @psalm-pure
7979
     *
7980
     * @return string
7981
     *                <p>A string after the replacements.</p>
7982
     */
7983 17
    public static function str_replace_ending(
7984
        string $str,
7985
        string $search,
7986
        string $replacement
7987
    ): string {
7988 17
        if ($str === '') {
7989 4
            if ($replacement === '') {
7990 2
                return '';
7991
            }
7992
7993 2
            if ($search === '') {
7994 2
                return $replacement;
7995
            }
7996
        }
7997
7998 13
        if ($search === '') {
7999 2
            return $str . $replacement;
8000
        }
8001
8002 11
        if (\strpos($str, $search, \strlen($str) - \strlen($search)) !== false) {
8003 8
            $str = \substr($str, 0, -\strlen($search)) . $replacement;
8004
        }
8005
8006 11
        return $str;
8007
    }
8008
8009
    /**
8010
     * Replace the first "$search"-term with the "$replace"-term.
8011
     *
8012
     * @param string $search
8013
     * @param string $replace
8014
     * @param string $subject
8015
     *
8016
     * @psalm-pure
8017
     *
8018
     * @return string
8019
     *
8020
     * @psalm-suppress InvalidReturnType
8021
     */
8022 2
    public static function str_replace_first(
8023
        string $search,
8024
        string $replace,
8025
        string $subject
8026
    ): string {
8027 2
        $pos = self::strpos($subject, $search);
8028
8029 2
        if ($pos !== false) {
8030
            /**
8031
             * @psalm-suppress InvalidReturnStatement
8032
             */
8033 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...
8034 2
                $subject,
8035 2
                $replace,
8036 2
                $pos,
8037 2
                (int) self::strlen($search)
8038
            );
8039
        }
8040
8041 2
        return $subject;
8042
    }
8043
8044
    /**
8045
     * Replace the last "$search"-term with the "$replace"-term.
8046
     *
8047
     * @param string $search
8048
     * @param string $replace
8049
     * @param string $subject
8050
     *
8051
     * @psalm-pure
8052
     *
8053
     * @return string
8054
     *
8055
     * @psalm-suppress InvalidReturnType
8056
     */
8057 2
    public static function str_replace_last(
8058
        string $search,
8059
        string $replace,
8060
        string $subject
8061
    ): string {
8062 2
        $pos = self::strrpos($subject, $search);
8063 2
        if ($pos !== false) {
8064
            /**
8065
             * @psalm-suppress InvalidReturnStatement
8066
             */
8067 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...
8068 2
                $subject,
8069 2
                $replace,
8070 2
                $pos,
8071 2
                (int) self::strlen($search)
8072
            );
8073
        }
8074
8075 2
        return $subject;
8076
    }
8077
8078
    /**
8079
     * Shuffles all the characters in the string.
8080
     *
8081
     * INFO: uses random algorithm which is weak for cryptography purposes
8082
     *
8083
     * EXAMPLE: <code>UTF8::str_shuffle('fòô bàř fòô'); // 'àòôřb ffòô '</code>
8084
     *
8085
     * @param string $str      <p>The input string</p>
8086
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
8087
     *
8088
     * @return string
8089
     *                <p>The shuffled string.</p>
8090
     */
8091 5
    public static function str_shuffle(string $str, string $encoding = 'UTF-8'): string
8092
    {
8093 5
        if ($encoding === 'UTF-8') {
8094 5
            $indexes = \range(0, (int) \mb_strlen($str) - 1);
8095
            /** @noinspection NonSecureShuffleUsageInspection */
8096 5
            \shuffle($indexes);
8097
8098
            // init
8099 5
            $shuffled_str = '';
8100
8101 5
            foreach ($indexes as &$i) {
8102 5
                $tmp_sub_str = \mb_substr($str, $i, 1);
8103 5
                if ($tmp_sub_str !== false) {
8104 5
                    $shuffled_str .= $tmp_sub_str;
8105
                }
8106
            }
8107
        } else {
8108
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8109
8110
            $indexes = \range(0, (int) self::strlen($str, $encoding) - 1);
8111
            /** @noinspection NonSecureShuffleUsageInspection */
8112
            \shuffle($indexes);
8113
8114
            // init
8115
            $shuffled_str = '';
8116
8117
            foreach ($indexes as &$i) {
8118
                $tmp_sub_str = self::substr($str, $i, 1, $encoding);
8119
                if ($tmp_sub_str !== false) {
8120
                    $shuffled_str .= $tmp_sub_str;
8121
                }
8122
            }
8123
        }
8124
8125 5
        return $shuffled_str;
8126
    }
8127
8128
    /**
8129
     * Returns the substring beginning at $start, and up to, but not including
8130
     * the index specified by $end. If $end is omitted, the function extracts
8131
     * the remaining string. If $end is negative, it is computed from the end
8132
     * of the string.
8133
     *
8134
     * @param string   $str
8135
     * @param int      $start    <p>Initial index from which to begin extraction.</p>
8136
     * @param int|null $end      [optional] <p>Index at which to end extraction. Default: null</p>
8137
     * @param string   $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
8138
     *
8139
     * @psalm-pure
8140
     *
8141
     * @return false|string
8142
     *                      <p>The extracted substring.</p><p>If <i>str</i> is shorter than <i>start</i>
8143
     *                      characters long, <b>FALSE</b> will be returned.
8144
     */
8145 18
    public static function str_slice(
8146
        string $str,
8147
        int $start,
8148
        int $end = null,
8149
        string $encoding = 'UTF-8'
8150
    ) {
8151 18
        if ($encoding === 'UTF-8') {
8152 7
            if ($end === null) {
8153 1
                $length = (int) \mb_strlen($str);
8154 6
            } elseif ($end >= 0 && $end <= $start) {
8155 2
                return '';
8156 4
            } elseif ($end < 0) {
8157 1
                $length = (int) \mb_strlen($str) + $end - $start;
8158
            } else {
8159 3
                $length = $end - $start;
8160
            }
8161
8162 5
            return \mb_substr($str, $start, $length);
8163
        }
8164
8165 11
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
8166
8167 11
        if ($end === null) {
8168 5
            $length = (int) self::strlen($str, $encoding);
8169 6
        } elseif ($end >= 0 && $end <= $start) {
8170 2
            return '';
8171 4
        } elseif ($end < 0) {
8172 1
            $length = (int) self::strlen($str, $encoding) + $end - $start;
8173
        } else {
8174 3
            $length = $end - $start;
8175
        }
8176
8177 9
        return self::substr($str, $start, $length, $encoding);
8178
    }
8179
8180
    /**
8181
     * Convert a string to e.g.: "snake_case"
8182
     *
8183
     * @param string $str
8184
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
8185
     *
8186
     * @psalm-pure
8187
     *
8188
     * @return string
8189
     *                <p>A string in snake_case.</p>
8190
     */
8191 22
    public static function str_snakeize(string $str, string $encoding = 'UTF-8'): string
8192
    {
8193 22
        if ($str === '') {
8194
            return '';
8195
        }
8196
8197 22
        $str = \str_replace(
8198 22
            '-',
8199 22
            '_',
8200 22
            self::normalize_whitespace($str)
8201
        );
8202
8203 22
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8204 19
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8205
        }
8206
8207 22
        $str = (string) \preg_replace_callback(
8208 22
            '/([\\p{N}|\\p{Lu}])/u',
8209
            /**
8210
             * @param string[] $matches
8211
             *
8212
             * @psalm-pure
8213
             *
8214
             * @return string
8215
             */
8216
            static function (array $matches) use ($encoding): string {
8217 9
                $match = $matches[1];
8218 9
                $match_int = (int) $match;
8219
8220 9
                if ((string) $match_int === $match) {
8221 4
                    return '_' . $match . '_';
8222
                }
8223
8224 5
                if ($encoding === 'UTF-8') {
8225 5
                    return '_' . \mb_strtolower($match);
8226
                }
8227
8228
                return '_' . self::strtolower($match, $encoding);
8229 22
            },
8230 22
            $str
8231
        );
8232
8233 22
        $str = (string) \preg_replace(
8234
            [
8235 22
                '/\\s+/u',           // convert spaces to "_"
8236
                '/^\\s+|\\s+$/u', // trim leading & trailing spaces
8237
                '/_+/',                 // remove double "_"
8238
            ],
8239
            [
8240 22
                '_',
8241
                '',
8242
                '_',
8243
            ],
8244 22
            $str
8245
        );
8246
8247 22
        return \trim(\trim($str, '_')); // trim leading & trailing "_" + whitespace
8248
    }
8249
8250
    /**
8251
     * Sort all characters according to code points.
8252
     *
8253
     * EXAMPLE: <code>UTF8::str_sort('  -ABC-中文空白-  '); // '    ---ABC中文白空'</code>
8254
     *
8255
     * @param string $str    <p>A UTF-8 string.</p>
8256
     * @param bool   $unique <p>Sort unique. If <strong>true</strong>, repeated characters are ignored.</p>
8257
     * @param bool   $desc   <p>If <strong>true</strong>, will sort characters in reverse code point order.</p>
8258
     *
8259
     * @psalm-pure
8260
     *
8261
     * @return string
8262
     *                <p>A string of sorted characters.</p>
8263
     */
8264 2
    public static function str_sort(string $str, bool $unique = false, bool $desc = false): string
8265
    {
8266 2
        $array = self::codepoints($str);
8267
8268 2
        if ($unique) {
8269 2
            $array = \array_flip(\array_flip($array));
8270
        }
8271
8272 2
        if ($desc) {
8273 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

8273
            \arsort(/** @scrutinizer ignore-type */ $array);
Loading history...
8274
        } else {
8275 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

8275
            \asort(/** @scrutinizer ignore-type */ $array);
Loading history...
8276
        }
8277
8278 2
        return self::string($array);
8279
    }
8280
8281
    /**
8282
     * Convert a string to an array of Unicode characters.
8283
     *
8284
     * EXAMPLE: <code>
8285
     * UTF8::str_split_array(['中文空白', 'test'], 2); // [['中文', '空白'], ['te', 'st']]
8286
     * </code>
8287
     *
8288
     * @param int[]|string[] $input                   <p>The string[] or int[] to split into array.</p>
8289
     * @param int            $length                  [optional] <p>Max character length of each array
8290
     *                                                lement.</p>
8291
     * @param bool           $clean_utf8              [optional] <p>Remove non UTF-8 chars from the
8292
     *                                                string.</p>
8293
     * @param bool           $try_to_use_mb_functions [optional] <p>Set to false, if you don't want to use
8294
     *                                                "mb_substr"</p>
8295
     *
8296
     * @psalm-pure
8297
     *
8298
     * @return string[][]
8299
     *                    <p>An array containing chunks of the input.</p>
8300
     */
8301 1
    public static function str_split_array(
8302
        array $input,
8303
        int $length = 1,
8304
        bool $clean_utf8 = false,
8305
        bool $try_to_use_mb_functions = true
8306
    ): array {
8307 1
        foreach ($input as $k => &$v) {
8308 1
            $v = self::str_split(
8309 1
                $v,
8310 1
                $length,
8311 1
                $clean_utf8,
8312 1
                $try_to_use_mb_functions
8313
            );
8314
        }
8315
8316
        /** @var string[][] $input */
8317 1
        return $input;
8318
    }
8319
8320
    /**
8321
     * Convert a string to an array of unicode characters.
8322
     *
8323
     * EXAMPLE: <code>UTF8::str_split('中文空白'); // array('中', '文', '空', '白')</code>
8324
     *
8325
     * @param int|string $input                   <p>The string or int to split into array.</p>
8326
     * @param int        $length                  [optional] <p>Max character length of each array
8327
     *                                            element.</p>
8328
     * @param bool       $clean_utf8              [optional] <p>Remove non UTF-8 chars from the
8329
     *                                            string.</p>
8330
     * @param bool       $try_to_use_mb_functions [optional] <p>Set to false, if you don't want to use
8331
     *                                            "mb_substr"</p>
8332
     *
8333
     * @psalm-pure
8334
     *
8335
     * @return string[]
8336
     *                  <p>An array containing chunks of chars from the input.</p>
8337
     *
8338
     * @noinspection SuspiciousBinaryOperationInspection
8339
     * @noinspection OffsetOperationsInspection
8340
     */
8341 90
    public static function str_split(
8342
        $input,
8343
        int $length = 1,
8344
        bool $clean_utf8 = false,
8345
        bool $try_to_use_mb_functions = true
8346
    ): array {
8347 90
        if ($length <= 0) {
8348 3
            return [];
8349
        }
8350
8351
        // this is only an old fallback
8352
        /** @noinspection PhpSillyAssignmentInspection - hack for phpstan */
8353
        /** @var int|int[]|string|string[] $input */
8354 89
        $input = $input;
8355 89
        if (\is_array($input)) {
8356
            /**
8357
             * @psalm-suppress InvalidReturnStatement
8358
             */
8359
            return self::str_split_array(
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::str_split_a...ry_to_use_mb_functions) returns the type array<mixed,string[]> which is incompatible with the documented return type string[].
Loading history...
8360
                $input,
8361
                $length,
8362
                $clean_utf8,
8363
                $try_to_use_mb_functions
8364
            );
8365
        }
8366
8367
        // init
8368 89
        $input = (string) $input;
8369
8370 89
        if ($input === '') {
8371 14
            return [];
8372
        }
8373
8374 86
        if ($clean_utf8) {
8375 19
            $input = self::clean($input);
8376
        }
8377
8378
        if (
8379 86
            $try_to_use_mb_functions
8380
            &&
8381 86
            self::$SUPPORT['mbstring'] === true
8382
        ) {
8383 82
            if (\function_exists('mb_str_split')) {
8384
                /**
8385
                 * @psalm-suppress ImpureFunctionCall - why?
8386
                 */
8387 82
                $return = \mb_str_split($input, $length);
8388 82
                if ($return !== false) {
8389 82
                    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...
8390
                }
8391
            }
8392
8393
            $i_max = \mb_strlen($input);
8394
            if ($i_max <= 127) {
8395
                $ret = [];
8396
                for ($i = 0; $i < $i_max; ++$i) {
8397
                    $ret[] = \mb_substr($input, $i, 1);
8398
                }
8399
            } else {
8400
                $return_array = [];
8401
                \preg_match_all('/./us', $input, $return_array);
8402
                $ret = $return_array[0] ?? [];
8403
            }
8404 23
        } elseif (self::$SUPPORT['pcre_utf8'] === true) {
8405 17
            $return_array = [];
8406 17
            \preg_match_all('/./us', $input, $return_array);
8407 17
            $ret = $return_array[0] ?? [];
8408
        } else {
8409
8410
            // fallback
8411
8412 8
            $ret = [];
8413 8
            $len = \strlen($input);
8414
8415
            /** @noinspection ForeachInvariantsInspection */
8416 8
            for ($i = 0; $i < $len; ++$i) {
8417 8
                if (($input[$i] & "\x80") === "\x00") {
8418 8
                    $ret[] = $input[$i];
8419
                } elseif (
8420 8
                    isset($input[$i + 1])
8421
                    &&
8422 8
                    ($input[$i] & "\xE0") === "\xC0"
8423
                ) {
8424 4
                    if (($input[$i + 1] & "\xC0") === "\x80") {
8425 4
                        $ret[] = $input[$i] . $input[$i + 1];
8426
8427 4
                        ++$i;
8428
                    }
8429
                } elseif (
8430 6
                    isset($input[$i + 2])
8431
                    &&
8432 6
                    ($input[$i] & "\xF0") === "\xE0"
8433
                ) {
8434
                    if (
8435 6
                        ($input[$i + 1] & "\xC0") === "\x80"
8436
                        &&
8437 6
                        ($input[$i + 2] & "\xC0") === "\x80"
8438
                    ) {
8439 6
                        $ret[] = $input[$i] . $input[$i + 1] . $input[$i + 2];
8440
8441 6
                        $i += 2;
8442
                    }
8443
                } elseif (
8444
                    isset($input[$i + 3])
8445
                    &&
8446
                    ($input[$i] & "\xF8") === "\xF0"
8447
                ) {
8448
                    if (
8449
                        ($input[$i + 1] & "\xC0") === "\x80"
8450
                        &&
8451
                        ($input[$i + 2] & "\xC0") === "\x80"
8452
                        &&
8453
                        ($input[$i + 3] & "\xC0") === "\x80"
8454
                    ) {
8455
                        $ret[] = $input[$i] . $input[$i + 1] . $input[$i + 2] . $input[$i + 3];
8456
8457
                        $i += 3;
8458
                    }
8459
                }
8460
            }
8461
        }
8462
8463 23
        if ($length > 1) {
8464 2
            $ret = \array_chunk($ret, $length);
8465
8466 2
            return \array_map(
8467
                static function (array $item): string {
8468 2
                    return \implode('', $item);
8469 2
                },
8470 2
                $ret
8471
            );
8472
        }
8473
8474 23
        if (isset($ret[0]) && $ret[0] === '') {
8475
            return [];
8476
        }
8477
8478 23
        return $ret;
8479
    }
8480
8481
    /**
8482
     * Splits the string with the provided regular expression, returning an
8483
     * array of strings. An optional integer $limit will truncate the
8484
     * results.
8485
     *
8486
     * @param string $str
8487
     * @param string $pattern <p>The regex with which to split the string.</p>
8488
     * @param int    $limit   [optional] <p>Maximum number of results to return. Default: -1 === no limit</p>
8489
     *
8490
     * @psalm-pure
8491
     *
8492
     * @return string[]
8493
     *                  <p>An array of strings.</p>
8494
     */
8495 16
    public static function str_split_pattern(string $str, string $pattern, int $limit = -1): array
8496
    {
8497 16
        if ($limit === 0) {
8498 2
            return [];
8499
        }
8500
8501 14
        if ($pattern === '') {
8502 1
            return [$str];
8503
        }
8504
8505 13
        if (self::$SUPPORT['mbstring'] === true) {
8506 13
            if ($limit >= 0) {
8507
                /** @noinspection PhpComposerExtensionStubsInspection */
8508 8
                $result_tmp = \mb_split($pattern, $str);
8509
8510 8
                $result = [];
8511 8
                foreach ($result_tmp as $item_tmp) {
8512 8
                    if ($limit === 0) {
8513 4
                        break;
8514
                    }
8515 8
                    --$limit;
8516
8517 8
                    $result[] = $item_tmp;
8518
                }
8519
8520 8
                return $result;
8521
            }
8522
8523
            /** @noinspection PhpComposerExtensionStubsInspection */
8524 5
            return \mb_split($pattern, $str);
8525
        }
8526
8527
        if ($limit > 0) {
8528
            ++$limit;
8529
        } else {
8530
            $limit = -1;
8531
        }
8532
8533
        $array = \preg_split('/' . \preg_quote($pattern, '/') . '/u', $str, $limit);
8534
8535
        if ($array === false) {
8536
            return [];
8537
        }
8538
8539
        if ($limit > 0 && \count($array) === $limit) {
8540
            \array_pop($array);
8541
        }
8542
8543
        return $array;
8544
    }
8545
8546
    /**
8547
     * Check if the string starts with the given substring.
8548
     *
8549
     * EXAMPLE: <code>
8550
     * UTF8::str_starts_with('ΚόσμεMiddleEnd', 'Κόσμε'); // true
8551
     * UTF8::str_starts_with('ΚόσμεMiddleEnd', 'κόσμε'); // false
8552
     * </code>
8553
     *
8554
     * @param string $haystack <p>The string to search in.</p>
8555
     * @param string $needle   <p>The substring to search for.</p>
8556
     *
8557
     * @psalm-pure
8558
     *
8559
     * @return bool
8560
     */
8561 19
    public static function str_starts_with(string $haystack, string $needle): bool
8562
    {
8563 19
        if ($needle === '') {
8564 2
            return true;
8565
        }
8566
8567 19
        if ($haystack === '') {
8568
            return false;
8569
        }
8570
8571 19
        return \strncmp($haystack, $needle, \strlen($needle)) === 0;
8572
    }
8573
8574
    /**
8575
     * Returns true if the string begins with any of $substrings, false otherwise.
8576
     *
8577
     * - case-sensitive
8578
     *
8579
     * @param string $str        <p>The input string.</p>
8580
     * @param array  $substrings <p>Substrings to look for.</p>
8581
     *
8582
     * @psalm-pure
8583
     *
8584
     * @return bool
8585
     *              <p>Whether or not $str starts with $substring.</p>
8586
     */
8587 8
    public static function str_starts_with_any(string $str, array $substrings): bool
8588
    {
8589 8
        if ($str === '') {
8590
            return false;
8591
        }
8592
8593 8
        if ($substrings === []) {
8594
            return false;
8595
        }
8596
8597 8
        foreach ($substrings as &$substring) {
8598 8
            if (self::str_starts_with($str, $substring)) {
8599 8
                return true;
8600
            }
8601
        }
8602
8603 6
        return false;
8604
    }
8605
8606
    /**
8607
     * Gets the substring after the first occurrence of a separator.
8608
     *
8609
     * @param string $str       <p>The input string.</p>
8610
     * @param string $separator <p>The string separator.</p>
8611
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
8612
     *
8613
     * @psalm-pure
8614
     *
8615
     * @return string
8616
     */
8617 1
    public static function str_substr_after_first_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
8618
    {
8619 1
        if ($separator === '' || $str === '') {
8620 1
            return '';
8621
        }
8622
8623 1
        if ($encoding === 'UTF-8') {
8624 1
            $offset = \mb_strpos($str, $separator);
8625 1
            if ($offset === false) {
8626 1
                return '';
8627
            }
8628
8629 1
            return (string) \mb_substr(
8630 1
                $str,
8631 1
                $offset + (int) \mb_strlen($separator)
8632
            );
8633
        }
8634
8635
        $offset = self::strpos($str, $separator, 0, $encoding);
8636
        if ($offset === false) {
8637
            return '';
8638
        }
8639
8640
        return (string) \mb_substr(
8641
            $str,
8642
            $offset + (int) self::strlen($separator, $encoding),
8643
            null,
8644
            $encoding
8645
        );
8646
    }
8647
8648
    /**
8649
     * Gets the substring after the last occurrence of a separator.
8650
     *
8651
     * @param string $str       <p>The input string.</p>
8652
     * @param string $separator <p>The string separator.</p>
8653
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
8654
     *
8655
     * @psalm-pure
8656
     *
8657
     * @return string
8658
     */
8659 1
    public static function str_substr_after_last_separator(
8660
        string $str,
8661
        string $separator,
8662
        string $encoding = 'UTF-8'
8663
    ): string {
8664 1
        if ($separator === '' || $str === '') {
8665 1
            return '';
8666
        }
8667
8668 1
        if ($encoding === 'UTF-8') {
8669 1
            $offset = \mb_strrpos($str, $separator);
8670 1
            if ($offset === false) {
8671 1
                return '';
8672
            }
8673
8674 1
            return (string) \mb_substr(
8675 1
                $str,
8676 1
                $offset + (int) \mb_strlen($separator)
8677
            );
8678
        }
8679
8680
        $offset = self::strrpos($str, $separator, 0, $encoding);
8681
        if ($offset === false) {
8682
            return '';
8683
        }
8684
8685
        return (string) self::substr(
8686
            $str,
8687
            $offset + (int) self::strlen($separator, $encoding),
8688
            null,
8689
            $encoding
8690
        );
8691
    }
8692
8693
    /**
8694
     * Gets the substring before the first occurrence of a separator.
8695
     *
8696
     * @param string $str       <p>The input string.</p>
8697
     * @param string $separator <p>The string separator.</p>
8698
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
8699
     *
8700
     * @psalm-pure
8701
     *
8702
     * @return string
8703
     */
8704 1
    public static function str_substr_before_first_separator(
8705
        string $str,
8706
        string $separator,
8707
        string $encoding = 'UTF-8'
8708
    ): string {
8709 1
        if ($separator === '' || $str === '') {
8710 1
            return '';
8711
        }
8712
8713 1
        if ($encoding === 'UTF-8') {
8714 1
            $offset = \mb_strpos($str, $separator);
8715 1
            if ($offset === false) {
8716 1
                return '';
8717
            }
8718
8719 1
            return (string) \mb_substr(
8720 1
                $str,
8721 1
                0,
8722 1
                $offset
8723
            );
8724
        }
8725
8726
        $offset = self::strpos($str, $separator, 0, $encoding);
8727
        if ($offset === false) {
8728
            return '';
8729
        }
8730
8731
        return (string) self::substr(
8732
            $str,
8733
            0,
8734
            $offset,
8735
            $encoding
8736
        );
8737
    }
8738
8739
    /**
8740
     * Gets the substring before the last occurrence of a separator.
8741
     *
8742
     * @param string $str       <p>The input string.</p>
8743
     * @param string $separator <p>The string separator.</p>
8744
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
8745
     *
8746
     * @psalm-pure
8747
     *
8748
     * @return string
8749
     */
8750 1
    public static function str_substr_before_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
8751
    {
8752 1
        if ($separator === '' || $str === '') {
8753 1
            return '';
8754
        }
8755
8756 1
        if ($encoding === 'UTF-8') {
8757 1
            $offset = \mb_strrpos($str, $separator);
8758 1
            if ($offset === false) {
8759 1
                return '';
8760
            }
8761
8762 1
            return (string) \mb_substr(
8763 1
                $str,
8764 1
                0,
8765 1
                $offset
8766
            );
8767
        }
8768
8769
        $offset = self::strrpos($str, $separator, 0, $encoding);
8770
        if ($offset === false) {
8771
            return '';
8772
        }
8773
8774
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
8775
8776
        return (string) self::substr(
8777
            $str,
8778
            0,
8779
            $offset,
8780
            $encoding
8781
        );
8782
    }
8783
8784
    /**
8785
     * Gets the substring after (or before via "$before_needle") the first occurrence of the "$needle".
8786
     *
8787
     * @param string $str           <p>The input string.</p>
8788
     * @param string $needle        <p>The string to look for.</p>
8789
     * @param bool   $before_needle [optional] <p>Default: false</p>
8790
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
8791
     *
8792
     * @psalm-pure
8793
     *
8794
     * @return string
8795
     */
8796 2
    public static function str_substr_first(
8797
        string $str,
8798
        string $needle,
8799
        bool $before_needle = false,
8800
        string $encoding = 'UTF-8'
8801
    ): string {
8802 2
        if ($str === '' || $needle === '') {
8803 2
            return '';
8804
        }
8805
8806 2
        if ($encoding === 'UTF-8') {
8807 2
            if ($before_needle) {
8808 1
                $part = \mb_strstr(
8809 1
                    $str,
8810 1
                    $needle,
8811 1
                    $before_needle
8812
                );
8813
            } else {
8814 1
                $part = \mb_strstr(
8815 1
                    $str,
8816 2
                    $needle
8817
                );
8818
            }
8819
        } else {
8820
            $part = self::strstr(
8821
                $str,
8822
                $needle,
8823
                $before_needle,
8824
                $encoding
8825
            );
8826
        }
8827
8828 2
        return $part === false ? '' : $part;
8829
    }
8830
8831
    /**
8832
     * Gets the substring after (or before via "$before_needle") the last occurrence of the "$needle".
8833
     *
8834
     * @param string $str           <p>The input string.</p>
8835
     * @param string $needle        <p>The string to look for.</p>
8836
     * @param bool   $before_needle [optional] <p>Default: false</p>
8837
     * @param string $encoding      [optional] <p>Default: 'UTF-8'</p>
8838
     *
8839
     * @psalm-pure
8840
     *
8841
     * @return string
8842
     */
8843 2
    public static function str_substr_last(
8844
        string $str,
8845
        string $needle,
8846
        bool $before_needle = false,
8847
        string $encoding = 'UTF-8'
8848
    ): string {
8849 2
        if ($str === '' || $needle === '') {
8850 2
            return '';
8851
        }
8852
8853 2
        if ($encoding === 'UTF-8') {
8854 2
            if ($before_needle) {
8855 1
                $part = \mb_strrchr(
8856 1
                    $str,
8857 1
                    $needle,
8858 1
                    $before_needle
8859
                );
8860
            } else {
8861 1
                $part = \mb_strrchr(
8862 1
                    $str,
8863 2
                    $needle
8864
                );
8865
            }
8866
        } else {
8867
            $part = self::strrchr(
8868
                $str,
8869
                $needle,
8870
                $before_needle,
8871
                $encoding
8872
            );
8873
        }
8874
8875 2
        return $part === false ? '' : $part;
8876
    }
8877
8878
    /**
8879
     * Surrounds $str with the given substring.
8880
     *
8881
     * @param string $str
8882
     * @param string $substring <p>The substring to add to both sides.</p>
8883
     *
8884
     * @psalm-pure
8885
     *
8886
     * @return string
8887
     *                <p>A string with the substring both prepended and appended.</p>
8888
     */
8889 5
    public static function str_surround(string $str, string $substring): string
8890
    {
8891 5
        return $substring . $str . $substring;
8892
    }
8893
8894
    /**
8895
     * Returns a trimmed string with the first letter of each word capitalized.
8896
     * Also accepts an array, $ignore, allowing you to list words not to be
8897
     * capitalized.
8898
     *
8899
     * @param string              $str
8900
     * @param array|string[]|null $ignore                        [optional] <p>An array of words not to capitalize or
8901
     *                                                           null. Default: null</p>
8902
     * @param string              $encoding                      [optional] <p>Default: 'UTF-8'</p>
8903
     * @param bool                $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the
8904
     *                                                           string.</p>
8905
     * @param string|null         $lang                          [optional] <p>Set the language for special cases: az,
8906
     *                                                           el, lt, tr</p>
8907
     * @param bool                $try_to_keep_the_string_length [optional] <p>true === try to keep the string length:
8908
     *                                                           e.g. ẞ -> ß</p>
8909
     * @param bool                $use_trim_first                [optional] <p>true === trim the input string,
8910
     *                                                           first</p>
8911
     * @param string|null         $word_define_chars             [optional] <p>An string of chars that will be used as
8912
     *                                                           whitespace separator === words.</p>
8913
     *
8914
     * @psalm-pure
8915
     *
8916
     * @return string
8917
     *                <p>The titleized string.</p>
8918
     *
8919
     * @noinspection PhpTooManyParametersInspection
8920
     */
8921 10
    public static function str_titleize(
8922
        string $str,
8923
        array $ignore = null,
8924
        string $encoding = 'UTF-8',
8925
        bool $clean_utf8 = false,
8926
        string $lang = null,
8927
        bool $try_to_keep_the_string_length = false,
8928
        bool $use_trim_first = true,
8929
        string $word_define_chars = null
8930
    ): string {
8931 10
        if ($str === '') {
8932
            return '';
8933
        }
8934
8935 10
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8936 9
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
8937
        }
8938
8939 10
        if ($use_trim_first) {
8940 10
            $str = \trim($str);
8941
        }
8942
8943 10
        if ($clean_utf8) {
8944
            $str = self::clean($str);
8945
        }
8946
8947 10
        $use_mb_functions = $lang === null && !$try_to_keep_the_string_length;
8948
8949 10
        if ($word_define_chars) {
8950 4
            $word_define_chars = \preg_quote($word_define_chars, '/');
8951
        } else {
8952 6
            $word_define_chars = '';
8953
        }
8954
8955 10
        $str = (string) \preg_replace_callback(
8956 10
            '/([^\\s' . $word_define_chars . ']+)/u',
8957
            static function (array $match) use ($try_to_keep_the_string_length, $lang, $ignore, $use_mb_functions, $encoding): string {
8958 10
                if ($ignore !== null && \in_array($match[0], $ignore, true)) {
8959 4
                    return $match[0];
8960
                }
8961
8962 10
                if ($use_mb_functions) {
8963 10
                    if ($encoding === 'UTF-8') {
8964 10
                        return \mb_strtoupper(\mb_substr($match[0], 0, 1))
8965 10
                               . \mb_strtolower(\mb_substr($match[0], 1));
8966
                    }
8967
8968
                    return \mb_strtoupper(\mb_substr($match[0], 0, 1, $encoding), $encoding)
8969
                           . \mb_strtolower(\mb_substr($match[0], 1, null, $encoding), $encoding);
8970
                }
8971
8972
                return self::ucfirst(
8973
                    self::strtolower(
8974
                        $match[0],
8975
                        $encoding,
8976
                        false,
8977
                        $lang,
8978
                        $try_to_keep_the_string_length
8979
                    ),
8980
                    $encoding,
8981
                    false,
8982
                    $lang,
8983
                    $try_to_keep_the_string_length
8984
                );
8985 10
            },
8986 10
            $str
8987
        );
8988
8989 10
        return $str;
8990
    }
8991
8992
    /**
8993
     * Convert a string into a obfuscate string.
8994
     *
8995
     * EXAMPLE: <code>
8996
     *
8997
     * UTF8::str_obfuscate('[email protected]', 0.5, '*', ['@', '.']); // e.g. "l***@m**lleke*.*r*"
8998
     * </code>
8999
     *
9000
     * @param string   $str
9001
     * @param float    $percent
9002
     * @param string   $obfuscateChar
9003
     * @param string[] $keepChars
9004
     *
9005
     * @psalm-pure
9006
     *
9007
     * @return string
9008
     *                <p>The obfuscate string.</p>
9009
     */
9010 1
    public static function str_obfuscate(
9011
        string $str,
9012
        float $percent = 0.5,
9013
        string $obfuscateChar = '*',
9014
        array $keepChars = []
9015
    ): string {
9016 1
        $obfuscateCharHelper = "\u{2603}";
9017 1
        $str = \str_replace($obfuscateChar, $obfuscateCharHelper, $str);
9018
9019 1
        $chars = self::chars($str);
9020 1
        $charsMax = \count($chars);
9021 1
        $charsMaxChange = \round($charsMax * $percent);
9022 1
        $charsCounter = 0;
9023 1
        $charKeyDone = [];
9024
9025 1
        while ($charsCounter < $charsMaxChange) {
9026 1
            foreach ($chars as $charKey => $char) {
9027 1
                if (isset($charKeyDone[$charKey])) {
9028 1
                    continue;
9029
                }
9030
9031 1
                if (\random_int(0, 100) > 50) {
9032 1
                    continue;
9033
                }
9034
9035 1
                if ($char === $obfuscateChar) {
9036
                    continue;
9037
                }
9038
9039 1
                ++$charsCounter;
9040 1
                $charKeyDone[$charKey] = true;
9041
9042 1
                if ($charsCounter > $charsMaxChange) {
9043
                    break;
9044
                }
9045
9046 1
                if (\in_array($char, $keepChars, true)) {
9047 1
                    continue;
9048
                }
9049
9050 1
                $chars[$charKey] = $obfuscateChar;
9051
            }
9052
        }
9053
9054 1
        $str = \implode('', $chars);
9055
9056 1
        return \str_replace($obfuscateCharHelper, $obfuscateChar, $str);
9057
    }
9058
9059
    /**
9060
     * Returns a trimmed string in proper title case.
9061
     *
9062
     * Also accepts an array, $ignore, allowing you to list words not to be
9063
     * capitalized.
9064
     *
9065
     * Adapted from John Gruber's script.
9066
     *
9067
     * @see https://gist.github.com/gruber/9f9e8650d68b13ce4d78
9068
     *
9069
     * @param string $str
9070
     * @param array  $ignore   <p>An array of words not to capitalize.</p>
9071
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
9072
     *
9073
     * @psalm-pure
9074
     *
9075
     * @return string
9076
     *                <p>The titleized string.</p>
9077
     */
9078 35
    public static function str_titleize_for_humans(
9079
        string $str,
9080
        array $ignore = [],
9081
        string $encoding = 'UTF-8'
9082
    ): string {
9083 35
        if ($str === '') {
9084
            return '';
9085
        }
9086
9087
        $small_words = [
9088 35
            '(?<!q&)a',
9089
            'an',
9090
            'and',
9091
            'as',
9092
            'at(?!&t)',
9093
            'but',
9094
            'by',
9095
            'en',
9096
            'for',
9097
            'if',
9098
            'in',
9099
            'of',
9100
            'on',
9101
            'or',
9102
            'the',
9103
            'to',
9104
            'v[.]?',
9105
            'via',
9106
            'vs[.]?',
9107
        ];
9108
9109 35
        if ($ignore !== []) {
9110 1
            $small_words = \array_merge($small_words, $ignore);
9111
        }
9112
9113 35
        $small_words_rx = \implode('|', $small_words);
9114 35
        $apostrophe_rx = '(?x: [\'’] [[:lower:]]* )?';
9115
9116 35
        $str = \trim($str);
9117
9118 35
        if (!self::has_lowercase($str)) {
9119 2
            $str = self::strtolower($str, $encoding);
9120
        }
9121
9122
        // the main substitutions
9123
        /** @noinspection RegExpDuplicateAlternationBranch - false-positive - https://youtrack.jetbrains.com/issue/WI-51002 */
9124 35
        $str = (string) \preg_replace_callback(
9125
            '~\\b (_*) (?:                                                           # 1. Leading underscore and
9126
                        ( (?<=[ ][/\\\\]) [[:alpha:]]+ [-_[:alpha:]/\\\\]+ |                # 2. file path or 
9127 35
                          [-_[:alpha:]]+ [@.:] [-_[:alpha:]@.:/]+ ' . $apostrophe_rx . ' )  #    URL, domain, or email
9128
                        |
9129 35
                        ( (?i: ' . $small_words_rx . ' ) ' . $apostrophe_rx . ' )           # 3. or small word (case-insensitive)
9130
                        |
9131 35
                        ( [[:alpha:]] [[:lower:]\'’()\[\]{}]* ' . $apostrophe_rx . ' )     # 4. or word w/o internal caps
9132
                        |
9133 35
                        ( [[:alpha:]] [[:alpha:]\'’()\[\]{}]* ' . $apostrophe_rx . ' )     # 5. or some other word
9134
                      ) (_*) \\b                                                          # 6. With trailing underscore
9135
                    ~ux',
9136
            /**
9137
             * @param string[] $matches
9138
             *
9139
             * @psalm-pure
9140
             *
9141
             * @return string
9142
             */
9143
            static function (array $matches) use ($encoding): string {
9144
                // preserve leading underscore
9145 35
                $str = $matches[1];
9146 35
                if ($matches[2]) {
9147
                    // preserve URLs, domains, emails and file paths
9148 5
                    $str .= $matches[2];
9149 35
                } elseif ($matches[3]) {
9150
                    // lower-case small words
9151 25
                    $str .= self::strtolower($matches[3], $encoding);
9152 35
                } elseif ($matches[4]) {
9153
                    // capitalize word w/o internal caps
9154 34
                    $str .= static::ucfirst($matches[4], $encoding);
9155
                } else {
9156
                    // preserve other kinds of word (iPhone)
9157 7
                    $str .= $matches[5];
9158
                }
9159
                // preserve trailing underscore
9160 35
                $str .= $matches[6];
9161
9162 35
                return $str;
9163 35
            },
9164 35
            $str
9165
        );
9166
9167
        // Exceptions for small words: capitalize at start of title...
9168 35
        $str = (string) \preg_replace_callback(
9169
            '~(  \\A [[:punct:]]*            # start of title...
9170
                      |  [:.;?!][ ]+                # or of subsentence...
9171
                      |  [ ][\'"“‘(\[][ ]* )        # or of inserted subphrase...
9172 35
                      ( ' . $small_words_rx . ' ) \\b # ...followed by small word
9173
                     ~uxi',
9174
            /**
9175
             * @param string[] $matches
9176
             *
9177
             * @psalm-pure
9178
             *
9179
             * @return string
9180
             */
9181
            static function (array $matches) use ($encoding): string {
9182 11
                return $matches[1] . static::ucfirst($matches[2], $encoding);
9183 35
            },
9184 35
            $str
9185
        );
9186
9187
        // ...and end of title
9188 35
        $str = (string) \preg_replace_callback(
9189 35
            '~\\b ( ' . $small_words_rx . ' ) # small word...
9190
                      (?= [[:punct:]]* \Z          # ...at the end of the title...
9191
                      |   [\'"’”)\]] [ ] )         # ...or of an inserted subphrase?
9192
                     ~uxi',
9193
            /**
9194
             * @param string[] $matches
9195
             *
9196
             * @psalm-pure
9197
             *
9198
             * @return string
9199
             */
9200
            static function (array $matches) use ($encoding): string {
9201 3
                return static::ucfirst($matches[1], $encoding);
9202 35
            },
9203 35
            $str
9204
        );
9205
9206
        // Exceptions for small words in hyphenated compound words.
9207
        // e.g. "in-flight" -> In-Flight
9208 35
        $str = (string) \preg_replace_callback(
9209
            '~\\b
9210
                        (?<! -)                   # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (in-flight)
9211 35
                        ( ' . $small_words_rx . ' )
9212
                        (?= -[[:alpha:]]+)        # lookahead for "-someword"
9213
                       ~uxi',
9214
            /**
9215
             * @param string[] $matches
9216
             *
9217
             * @psalm-pure
9218
             *
9219
             * @return string
9220
             */
9221
            static function (array $matches) use ($encoding): string {
9222
                return static::ucfirst($matches[1], $encoding);
9223 35
            },
9224 35
            $str
9225
        );
9226
9227
        // e.g. "Stand-in" -> "Stand-In" (Stand is already capped at this point)
9228 35
        $str = (string) \preg_replace_callback(
9229
            '~\\b
9230
                      (?<!…)                    # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (stand-in)
9231
                      ( [[:alpha:]]+- )         # $1 = first word and hyphen, should already be properly capped
9232 35
                      ( ' . $small_words_rx . ' ) # ...followed by small word
9233
                      (?!	- )                 # Negative lookahead for another -
9234
                     ~uxi',
9235
            /**
9236
             * @param string[] $matches
9237
             *
9238
             * @psalm-pure
9239
             *
9240
             * @return string
9241
             */
9242
            static function (array $matches) use ($encoding): string {
9243
                return $matches[1] . static::ucfirst($matches[2], $encoding);
9244 35
            },
9245 35
            $str
9246
        );
9247
9248 35
        return $str;
9249
    }
9250
9251
    /**
9252
     * Get a binary representation of a specific string.
9253
     *
9254
     * EXAPLE: <code>UTF8::str_to_binary('😃'); // '11110000100111111001100010000011'</code>
9255
     *
9256
     * @param string $str <p>The input string.</p>
9257
     *
9258
     * @psalm-pure
9259
     *
9260
     * @return false|string
9261
     *                      <p>false on error</p>
9262
     */
9263 2
    public static function str_to_binary(string $str)
9264
    {
9265
        /** @var array|false $value - needed for PhpStan (stubs error) */
9266 2
        $value = \unpack('H*', $str);
9267 2
        if ($value === false) {
9268
            return false;
9269
        }
9270
9271
        /** @noinspection OffsetOperationsInspection */
9272 2
        return \base_convert($value[1], 16, 2);
9273
    }
9274
9275
    /**
9276
     * @param string   $str
9277
     * @param bool     $remove_empty_values <p>Remove empty values.</p>
9278
     * @param int|null $remove_short_values <p>The min. string length or null to disable</p>
9279
     *
9280
     * @psalm-pure
9281
     *
9282
     * @return string[]
9283
     */
9284 17
    public static function str_to_lines(string $str, bool $remove_empty_values = false, int $remove_short_values = null): array
9285
    {
9286 17
        if ($str === '') {
9287 1
            return $remove_empty_values ? [] : [''];
9288
        }
9289
9290 16
        if (self::$SUPPORT['mbstring'] === true) {
9291
            /** @noinspection PhpComposerExtensionStubsInspection */
9292 16
            $return = \mb_split("[\r\n]{1,2}", $str);
9293
        } else {
9294
            $return = \preg_split("/[\r\n]{1,2}/u", $str);
9295
        }
9296
9297 16
        if ($return === false) {
9298
            return $remove_empty_values ? [] : [''];
9299
        }
9300
9301
        if (
9302 16
            $remove_short_values === null
9303
            &&
9304 16
            !$remove_empty_values
9305
        ) {
9306 16
            return $return;
9307
        }
9308
9309
        return self::reduce_string_array(
9310
            $return,
9311
            $remove_empty_values,
9312
            $remove_short_values
9313
        );
9314
    }
9315
9316
    /**
9317
     * Convert a string into an array of words.
9318
     *
9319
     * EXAMPLE: <code>UTF8::str_to_words('中文空白 oöäü#s', '#') // array('', '中文空白', ' ', 'oöäü#s', '')</code>
9320
     *
9321
     * @param string   $str
9322
     * @param string   $char_list           <p>Additional chars for the definition of "words".</p>
9323
     * @param bool     $remove_empty_values <p>Remove empty values.</p>
9324
     * @param int|null $remove_short_values <p>The min. string length or null to disable</p>
9325
     *
9326
     * @psalm-pure
9327
     *
9328
     * @return string[]
9329
     */
9330 13
    public static function str_to_words(
9331
        string $str,
9332
        string $char_list = '',
9333
        bool $remove_empty_values = false,
9334
        int $remove_short_values = null
9335
    ): array {
9336 13
        if ($str === '') {
9337 4
            return $remove_empty_values ? [] : [''];
9338
        }
9339
9340 13
        $char_list = self::rxClass($char_list, '\pL');
9341
9342 13
        $return = \preg_split("/({$char_list}+(?:[\p{Pd}’']{$char_list}+)*)/u", $str, -1, \PREG_SPLIT_DELIM_CAPTURE);
9343 13
        if ($return === false) {
9344
            return $remove_empty_values ? [] : [''];
9345
        }
9346
9347
        if (
9348 13
            $remove_short_values === null
9349
            &&
9350 13
            !$remove_empty_values
9351
        ) {
9352 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...
9353
        }
9354
9355 2
        $tmp_return = self::reduce_string_array(
9356 2
            $return,
9357 2
            $remove_empty_values,
9358 2
            $remove_short_values
9359
        );
9360
9361 2
        foreach ($tmp_return as &$item) {
9362 2
            $item = (string) $item;
9363
        }
9364
9365 2
        return $tmp_return;
9366
    }
9367
9368
    /**
9369
     * alias for "UTF8::to_ascii()"
9370
     *
9371
     * @param string $str
9372
     * @param string $unknown
9373
     * @param bool   $strict
9374
     *
9375
     * @psalm-pure
9376
     *
9377
     * @return string
9378
     *
9379
     * @see        UTF8::to_ascii()
9380
     * @deprecated <p>please use "UTF8::to_ascii()"</p>
9381
     */
9382 7
    public static function str_transliterate(
9383
        string $str,
9384
        string $unknown = '?',
9385
        bool $strict = false
9386
    ): string {
9387 7
        return self::to_ascii($str, $unknown, $strict);
9388
    }
9389
9390
    /**
9391
     * Truncates the string to a given length. If $substring is provided, and
9392
     * truncating occurs, the string is further truncated so that the substring
9393
     * may be appended without exceeding the desired length.
9394
     *
9395
     * @param string $str
9396
     * @param int    $length    <p>Desired length of the truncated string.</p>
9397
     * @param string $substring [optional] <p>The substring to append if it can fit. Default: ''</p>
9398
     * @param string $encoding  [optional] <p>Default: 'UTF-8'</p>
9399
     *
9400
     * @psalm-pure
9401
     *
9402
     * @return string
9403
     *                <p>A string after truncating.</p>
9404
     */
9405 22
    public static function str_truncate(
9406
        string $str,
9407
        int $length,
9408
        string $substring = '',
9409
        string $encoding = 'UTF-8'
9410
    ): string {
9411 22
        if ($str === '') {
9412
            return '';
9413
        }
9414
9415 22
        if ($encoding === 'UTF-8') {
9416 10
            if ($length >= (int) \mb_strlen($str)) {
9417 2
                return $str;
9418
            }
9419
9420 8
            if ($substring !== '') {
9421 4
                $length -= (int) \mb_strlen($substring);
9422
9423
                /** @noinspection UnnecessaryCastingInspection */
9424 4
                return (string) \mb_substr($str, 0, $length) . $substring;
9425
            }
9426
9427
            /** @noinspection UnnecessaryCastingInspection */
9428 4
            return (string) \mb_substr($str, 0, $length);
9429
        }
9430
9431 12
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
9432
9433 12
        if ($length >= (int) self::strlen($str, $encoding)) {
9434 2
            return $str;
9435
        }
9436
9437 10
        if ($substring !== '') {
9438 6
            $length -= (int) self::strlen($substring, $encoding);
9439
        }
9440
9441
        return (
9442 10
               (string) self::substr(
9443 10
                   $str,
9444 10
                   0,
9445 10
                   $length,
9446 10
                   $encoding
9447
               )
9448 10
               ) . $substring;
9449
    }
9450
9451
    /**
9452
     * Truncates the string to a given length, while ensuring that it does not
9453
     * split words. If $substring is provided, and truncating occurs, the
9454
     * string is further truncated so that the substring may be appended without
9455
     * exceeding the desired length.
9456
     *
9457
     * @param string $str
9458
     * @param int    $length                                 <p>Desired length of the truncated string.</p>
9459
     * @param string $substring                              [optional] <p>The substring to append if it can fit.
9460
     *                                                       Default:
9461
     *                                                       ''</p>
9462
     * @param string $encoding                               [optional] <p>Default: 'UTF-8'</p>
9463
     * @param bool   $ignore_do_not_split_words_for_one_word [optional] <p>Default: false</p>
9464
     *
9465
     * @psalm-pure
9466
     *
9467
     * @return string
9468
     *                <p>A string after truncating.</p>
9469
     */
9470 47
    public static function str_truncate_safe(
9471
        string $str,
9472
        int $length,
9473
        string $substring = '',
9474
        string $encoding = 'UTF-8',
9475
        bool $ignore_do_not_split_words_for_one_word = false
9476
    ): string {
9477 47
        if ($str === '' || $length <= 0) {
9478 1
            return $substring;
9479
        }
9480
9481 47
        if ($encoding === 'UTF-8') {
9482 21
            if ($length >= (int) \mb_strlen($str)) {
9483 5
                return $str;
9484
            }
9485
9486
            // need to further trim the string so we can append the substring
9487 17
            $length -= (int) \mb_strlen($substring);
9488 17
            if ($length <= 0) {
9489 1
                return $substring;
9490
            }
9491
9492
            /** @var false|string $truncated - needed for PhpStan (stubs error) */
9493 17
            $truncated = \mb_substr($str, 0, $length);
9494 17
            if ($truncated === false) {
9495
                return '';
9496
            }
9497
9498
            // if the last word was truncated
9499 17
            $space_position = \mb_strpos($str, ' ', $length - 1);
9500 17
            if ($space_position !== $length) {
9501
                // find pos of the last occurrence of a space, get up to that
9502 13
                $last_position = \mb_strrpos($truncated, ' ', 0);
9503
9504
                if (
9505 13
                    $last_position !== false
9506
                    ||
9507
                    (
9508 3
                        $space_position !== false
9509
                        &&
9510 13
                         !$ignore_do_not_split_words_for_one_word
9511
                    )
9512
                ) {
9513 17
                    $truncated = (string) \mb_substr($truncated, 0, (int) $last_position);
9514
                }
9515
            }
9516
        } else {
9517 26
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9518
9519 26
            if ($length >= (int) self::strlen($str, $encoding)) {
9520 4
                return $str;
9521
            }
9522
9523
            // need to further trim the string so we can append the substring
9524 22
            $length -= (int) self::strlen($substring, $encoding);
9525 22
            if ($length <= 0) {
9526
                return $substring;
9527
            }
9528
9529 22
            $truncated = self::substr($str, 0, $length, $encoding);
9530
9531 22
            if ($truncated === false) {
9532
                return '';
9533
            }
9534
9535
            // if the last word was truncated
9536 22
            $space_position = self::strpos($str, ' ', $length - 1, $encoding);
9537 22
            if ($space_position !== $length) {
9538
                // find pos of the last occurrence of a space, get up to that
9539 12
                $last_position = self::strrpos($truncated, ' ', 0, $encoding);
9540
9541
                if (
9542 12
                    $last_position !== false
9543
                    ||
9544
                    (
9545 4
                        $space_position !== false
9546
                        &&
9547 12
                        !$ignore_do_not_split_words_for_one_word
9548
                    )
9549
                ) {
9550 9
                    $truncated = (string) self::substr($truncated, 0, (int) $last_position, $encoding);
9551
                }
9552
            }
9553
        }
9554
9555 39
        return $truncated . $substring;
9556
    }
9557
9558
    /**
9559
     * Returns a lowercase and trimmed string separated by underscores.
9560
     * Underscores are inserted before uppercase characters (with the exception
9561
     * of the first character of the string), and in place of spaces as well as
9562
     * dashes.
9563
     *
9564
     * @param string $str
9565
     *
9566
     * @psalm-pure
9567
     *
9568
     * @return string
9569
     *                <p>The underscored string.</p>
9570
     */
9571 16
    public static function str_underscored(string $str): string
9572
    {
9573 16
        return self::str_delimit($str, '_');
9574
    }
9575
9576
    /**
9577
     * Returns an UpperCamelCase version of the supplied string. It trims
9578
     * surrounding spaces, capitalizes letters following digits, spaces, dashes
9579
     * and underscores, and removes spaces, dashes, underscores.
9580
     *
9581
     * @param string      $str                           <p>The input string.</p>
9582
     * @param string      $encoding                      [optional] <p>Default: 'UTF-8'</p>
9583
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
9584
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
9585
     *                                                   tr</p>
9586
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
9587
     *                                                   -> ß</p>
9588
     *
9589
     * @psalm-pure
9590
     *
9591
     * @return string
9592
     *                <p>A string in UpperCamelCase.</p>
9593
     */
9594 13
    public static function str_upper_camelize(
9595
        string $str,
9596
        string $encoding = 'UTF-8',
9597
        bool $clean_utf8 = false,
9598
        string $lang = null,
9599
        bool $try_to_keep_the_string_length = false
9600
    ): string {
9601 13
        return self::ucfirst(self::str_camelize($str, $encoding), $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length);
9602
    }
9603
9604
    /**
9605
     * alias for "UTF8::ucfirst()"
9606
     *
9607
     * @param string      $str
9608
     * @param string      $encoding
9609
     * @param bool        $clean_utf8
9610
     * @param string|null $lang
9611
     * @param bool        $try_to_keep_the_string_length
9612
     *
9613
     * @psalm-pure
9614
     *
9615
     * @return string
9616
     *
9617
     * @see        UTF8::ucfirst()
9618
     * @deprecated <p>please use "UTF8::ucfirst()"</p>
9619
     */
9620 5
    public static function str_upper_first(
9621
        string $str,
9622
        string $encoding = 'UTF-8',
9623
        bool $clean_utf8 = false,
9624
        string $lang = null,
9625
        bool $try_to_keep_the_string_length = false
9626
    ): string {
9627 5
        return self::ucfirst(
9628 5
            $str,
9629 5
            $encoding,
9630 5
            $clean_utf8,
9631 5
            $lang,
9632 5
            $try_to_keep_the_string_length
9633
        );
9634
    }
9635
9636
    /**
9637
     * Get the number of words in a specific string.
9638
     *
9639
     * EXAMPLES: <code>
9640
     * // format: 0 -> return only word count (int)
9641
     * //
9642
     * UTF8::str_word_count('中文空白 öäü abc#c'); // 4
9643
     * UTF8::str_word_count('中文空白 öäü abc#c', 0, '#'); // 3
9644
     *
9645
     * // format: 1 -> return words (array)
9646
     * //
9647
     * UTF8::str_word_count('中文空白 öäü abc#c', 1); // array('中文空白', 'öäü', 'abc', 'c')
9648
     * UTF8::str_word_count('中文空白 öäü abc#c', 1, '#'); // array('中文空白', 'öäü', 'abc#c')
9649
     *
9650
     * // format: 2 -> return words with offset (array)
9651
     * //
9652
     * UTF8::str_word_count('中文空白 öäü ab#c', 2); // array(0 => '中文空白', 5 => 'öäü', 9 => 'abc', 13 => 'c')
9653
     * UTF8::str_word_count('中文空白 öäü ab#c', 2, '#'); // array(0 => '中文空白', 5 => 'öäü', 9 => 'abc#c')
9654
     * </code>
9655
     *
9656
     * @param string $str       <p>The input string.</p>
9657
     * @param int    $format    [optional] <p>
9658
     *                          <strong>0</strong> => return a number of words (default)<br>
9659
     *                          <strong>1</strong> => return an array of words<br>
9660
     *                          <strong>2</strong> => return an array of words with word-offset as key
9661
     *                          </p>
9662
     * @param string $char_list [optional] <p>Additional chars that contains to words and do not start a new word.</p>
9663
     *
9664
     * @psalm-pure
9665
     *
9666
     * @return int|string[]
9667
     *                      <p>The number of words in the string.</p>
9668
     */
9669 2
    public static function str_word_count(string $str, int $format = 0, string $char_list = '')
9670
    {
9671 2
        $str_parts = self::str_to_words($str, $char_list);
9672
9673 2
        $len = \count($str_parts);
9674
9675 2
        if ($format === 1) {
9676 2
            $number_of_words = [];
9677 2
            for ($i = 1; $i < $len; $i += 2) {
9678 2
                $number_of_words[] = $str_parts[$i];
9679
            }
9680 2
        } elseif ($format === 2) {
9681 2
            $number_of_words = [];
9682 2
            $offset = (int) self::strlen($str_parts[0]);
9683 2
            for ($i = 1; $i < $len; $i += 2) {
9684 2
                $number_of_words[$offset] = $str_parts[$i];
9685 2
                $offset += (int) self::strlen($str_parts[$i]) + (int) self::strlen($str_parts[$i + 1]);
9686
            }
9687
        } else {
9688 2
            $number_of_words = (int) (($len - 1) / 2);
9689
        }
9690
9691 2
        return $number_of_words;
9692
    }
9693
9694
    /**
9695
     * Case-insensitive string comparison.
9696
     *
9697
     * INFO: Case-insensitive version of UTF8::strcmp()
9698
     *
9699
     * EXAMPLE: <code>UTF8::strcasecmp("iñtërnâtiôn\nàlizætiøn", "Iñtërnâtiôn\nàlizætiøn"); // 0</code>
9700
     *
9701
     * @param string $str1     <p>The first string.</p>
9702
     * @param string $str2     <p>The second string.</p>
9703
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
9704
     *
9705
     * @psalm-pure
9706
     *
9707
     * @return int
9708
     *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
9709
     *             <strong>&gt; 0</strong> if str1 is greater than str2,<br>
9710
     *             <strong>0</strong> if they are equal
9711
     */
9712 23
    public static function strcasecmp(
9713
        string $str1,
9714
        string $str2,
9715
        string $encoding = 'UTF-8'
9716
    ): int {
9717 23
        return self::strcmp(
9718 23
            self::strtocasefold(
9719 23
                $str1,
9720 23
                true,
9721 23
                false,
9722 23
                $encoding,
9723 23
                null,
9724 23
                false
9725
            ),
9726 23
            self::strtocasefold(
9727 23
                $str2,
9728 23
                true,
9729 23
                false,
9730 23
                $encoding,
9731 23
                null,
9732 23
                false
9733
            )
9734
        );
9735
    }
9736
9737
    /**
9738
     * alias for "UTF8::strstr()"
9739
     *
9740
     * @param string $haystack
9741
     * @param string $needle
9742
     * @param bool   $before_needle
9743
     * @param string $encoding
9744
     * @param bool   $clean_utf8
9745
     *
9746
     * @psalm-pure
9747
     *
9748
     * @return false|string
9749
     *
9750
     * @see        UTF8::strstr()
9751
     * @deprecated <p>please use "UTF8::strstr()"</p>
9752
     */
9753 2
    public static function strchr(
9754
        string $haystack,
9755
        string $needle,
9756
        bool $before_needle = false,
9757
        string $encoding = 'UTF-8',
9758
        bool $clean_utf8 = false
9759
    ) {
9760 2
        return self::strstr(
9761 2
            $haystack,
9762 2
            $needle,
9763 2
            $before_needle,
9764 2
            $encoding,
9765 2
            $clean_utf8
9766
        );
9767
    }
9768
9769
    /**
9770
     * Case-sensitive string comparison.
9771
     *
9772
     * EXAMPLE: <code>UTF8::strcmp("iñtërnâtiôn\nàlizætiøn", "iñtërnâtiôn\nàlizætiøn"); // 0</code>
9773
     *
9774
     * @param string $str1 <p>The first string.</p>
9775
     * @param string $str2 <p>The second string.</p>
9776
     *
9777
     * @psalm-pure
9778
     *
9779
     * @return int
9780
     *             <strong>&lt; 0</strong> if str1 is less than str2<br>
9781
     *             <strong>&gt; 0</strong> if str1 is greater than str2<br>
9782
     *             <strong>0</strong> if they are equal
9783
     */
9784 29
    public static function strcmp(string $str1, string $str2): int
9785
    {
9786 29
        if ($str1 === $str2) {
9787 21
            return 0;
9788
        }
9789
9790 24
        return \strcmp(
9791 24
            \Normalizer::normalize($str1, \Normalizer::NFD),
9792 24
            \Normalizer::normalize($str2, \Normalizer::NFD)
9793
        );
9794
    }
9795
9796
    /**
9797
     * Find length of initial segment not matching mask.
9798
     *
9799
     * @param string   $str
9800
     * @param string   $char_list
9801
     * @param int      $offset
9802
     * @param int|null $length
9803
     * @param string   $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
9804
     *
9805
     * @psalm-pure
9806
     *
9807
     * @return int
9808
     */
9809 12
    public static function strcspn(
9810
        string $str,
9811
        string $char_list,
9812
        int $offset = 0,
9813
        int $length = null,
9814
        string $encoding = 'UTF-8'
9815
    ): int {
9816 12
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9817
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
9818
        }
9819
9820 12
        if ($char_list === '') {
9821 2
            return (int) self::strlen($str, $encoding);
9822
        }
9823
9824 11
        if ($offset || $length !== null) {
9825 3
            if ($encoding === 'UTF-8') {
9826 3
                if ($length === null) {
9827 2
                    $str_tmp = \mb_substr($str, $offset);
9828
                } else {
9829 3
                    $str_tmp = \mb_substr($str, $offset, $length);
9830
                }
9831
            } else {
9832
                $str_tmp = self::substr($str, $offset, $length, $encoding);
9833
            }
9834
9835 3
            if ($str_tmp === false) {
9836
                return 0;
9837
            }
9838
9839
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
9840 3
            $str = $str_tmp;
9841
        }
9842
9843 11
        if ($str === '') {
9844 2
            return 0;
9845
        }
9846
9847 10
        $matches = [];
9848 10
        if (\preg_match('/^(.*?)' . self::rxClass($char_list) . '/us', $str, $matches)) {
9849 9
            $return = self::strlen($matches[1], $encoding);
9850 9
            if ($return === false) {
9851
                return 0;
9852
            }
9853
9854 9
            return $return;
9855
        }
9856
9857 2
        return (int) self::strlen($str, $encoding);
9858
    }
9859
9860
    /**
9861
     * alias for "UTF8::stristr()"
9862
     *
9863
     * @param string $haystack
9864
     * @param string $needle
9865
     * @param bool   $before_needle
9866
     * @param string $encoding
9867
     * @param bool   $clean_utf8
9868
     *
9869
     * @psalm-pure
9870
     *
9871
     * @return false|string
9872
     *
9873
     * @see        UTF8::stristr()
9874
     * @deprecated <p>please use "UTF8::stristr()"</p>
9875
     */
9876 1
    public static function strichr(
9877
        string $haystack,
9878
        string $needle,
9879
        bool $before_needle = false,
9880
        string $encoding = 'UTF-8',
9881
        bool $clean_utf8 = false
9882
    ) {
9883 1
        return self::stristr(
9884 1
            $haystack,
9885 1
            $needle,
9886 1
            $before_needle,
9887 1
            $encoding,
9888 1
            $clean_utf8
9889
        );
9890
    }
9891
9892
    /**
9893
     * Create a UTF-8 string from code points.
9894
     *
9895
     * INFO: opposite to UTF8::codepoints()
9896
     *
9897
     * EXAMPLE: <code>UTF8::string(array(246, 228, 252)); // 'öäü'</code>
9898
     *
9899
     * @param int|int[]|string|string[] $intOrHex <p>Integer or Hexadecimal codepoints.</p>
9900
     *
9901
     * @phpstan-param int[]|numeric-string[]|int|numeric-string $intOrHex
9902
     *
9903
     * @psalm-pure
9904
     *
9905
     * @return string
9906
     *                <p>A UTF-8 encoded string.</p>
9907
     */
9908 4
    public static function string($intOrHex): string
9909
    {
9910 4
        if ($intOrHex === []) {
9911 4
            return '';
9912
        }
9913
9914 4
        if (!\is_array($intOrHex)) {
9915 1
            $intOrHex = [$intOrHex];
9916
        }
9917
9918 4
        $str = '';
9919 4
        foreach ($intOrHex as $strPart) {
9920 4
            $str .= '&#' . (int) $strPart . ';';
9921
        }
9922
9923 4
        return self::html_entity_decode($str, \ENT_QUOTES | \ENT_HTML5);
9924
    }
9925
9926
    /**
9927
     * Checks if string starts with "BOM" (Byte Order Mark Character) character.
9928
     *
9929
     * EXAMPLE: <code>UTF8::string_has_bom("\xef\xbb\xbf foobar"); // true</code>
9930
     *
9931
     * @param string $str <p>The input string.</p>
9932
     *
9933
     * @psalm-pure
9934
     *
9935
     * @return bool
9936
     *              <p>
9937
     *              <strong>true</strong> if the string has BOM at the start,<br>
9938
     *              <strong>false</strong> otherwise
9939
     *              </p>
9940
     */
9941 6
    public static function string_has_bom(string $str): bool
9942
    {
9943
        /** @noinspection PhpUnusedLocalVariableInspection */
9944 6
        foreach (self::$BOM as $bom_string => &$bom_byte_length) {
9945 6
            if (\strncmp($str, $bom_string, $bom_byte_length) === 0) {
9946 6
                return true;
9947
            }
9948
        }
9949
9950 6
        return false;
9951
    }
9952
9953
    /**
9954
     * Strip HTML and PHP tags from a string + clean invalid UTF-8.
9955
     *
9956
     * EXAMPLE: <code>UTF8::strip_tags("<span>κόσμε\xa0\xa1</span>"); // 'κόσμε'</code>
9957
     *
9958
     * @see http://php.net/manual/en/function.strip-tags.php
9959
     *
9960
     * @param string      $str            <p>
9961
     *                                    The input string.
9962
     *                                    </p>
9963
     * @param string|null $allowable_tags [optional] <p>
9964
     *                                    You can use the optional second parameter to specify tags which should
9965
     *                                    not be stripped.
9966
     *                                    </p>
9967
     *                                    <p>
9968
     *                                    HTML comments and PHP tags are also stripped. This is hardcoded and
9969
     *                                    can not be changed with allowable_tags.
9970
     *                                    </p>
9971
     * @param bool        $clean_utf8     [optional] <p>Remove non UTF-8 chars from the string.</p>
9972
     *
9973
     * @psalm-pure
9974
     *
9975
     * @return string
9976
     *                <p>The stripped string.</p>
9977
     */
9978 4
    public static function strip_tags(
9979
        string $str,
9980
        string $allowable_tags = null,
9981
        bool $clean_utf8 = false
9982
    ): string {
9983 4
        if ($str === '') {
9984 1
            return '';
9985
        }
9986
9987 4
        if ($clean_utf8) {
9988 2
            $str = self::clean($str);
9989
        }
9990
9991 4
        if ($allowable_tags === null) {
9992 4
            return \strip_tags($str);
9993
        }
9994
9995 2
        return \strip_tags($str, $allowable_tags);
9996
    }
9997
9998
    /**
9999
     * Strip all whitespace characters. This includes tabs and newline
10000
     * characters, as well as multibyte whitespace such as the thin space
10001
     * and ideographic space.
10002
     *
10003
     * EXAMPLE: <code>UTF8::strip_whitespace('   Ο     συγγραφέας  '); // 'Οσυγγραφέας'</code>
10004
     *
10005
     * @param string $str
10006
     *
10007
     * @psalm-pure
10008
     *
10009
     * @return string
10010
     */
10011 36
    public static function strip_whitespace(string $str): string
10012
    {
10013 36
        if ($str === '') {
10014 3
            return '';
10015
        }
10016
10017 33
        return (string) \preg_replace('/[[:space:]]+/u', '', $str);
10018
    }
10019
10020
    /**
10021
     * Find the position of the first occurrence of a substring in a string, case-insensitive.
10022
     *
10023
     * INFO: use UTF8::stripos_in_byte() for the byte-length
10024
     *
10025
     * EXAMPLE: <code>UTF8::stripos('aσσb', 'ΣΣ'); // 1</code> (σσ == ΣΣ)
10026
     *
10027
     * @see http://php.net/manual/en/function.mb-stripos.php
10028
     *
10029
     * @param string $haystack   <p>The string from which to get the position of the first occurrence of needle.</p>
10030
     * @param string $needle     <p>The string to find in haystack.</p>
10031
     * @param int    $offset     [optional] <p>The position in haystack to start searching.</p>
10032
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
10033
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
10034
     *
10035
     * @psalm-pure
10036
     *
10037
     * @return false|int
10038
     *                   Return the <strong>(int)</strong> numeric position of the first occurrence of needle in the
10039
     *                   haystack string,<br> or <strong>false</strong> if needle is not found
10040
     */
10041 25
    public static function stripos(
10042
        string $haystack,
10043
        string $needle,
10044
        int $offset = 0,
10045
        string $encoding = 'UTF-8',
10046
        bool $clean_utf8 = false
10047
    ) {
10048 25
        if ($haystack === '') {
10049 5
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
10050
                return 0;
10051
            }
10052
10053 5
            return false;
10054
        }
10055
10056 24
        if ($needle === '' && \PHP_VERSION_ID < 80000) {
10057 2
            return false;
10058
        }
10059
10060 24
        if ($clean_utf8) {
10061
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10062
            // if invalid characters are found in $haystack before $needle
10063 1
            $haystack = self::clean($haystack);
10064 1
            $needle = self::clean($needle);
10065
        }
10066
10067 24
        if (self::$SUPPORT['mbstring'] === true) {
10068 24
            if ($encoding === 'UTF-8') {
10069 24
                return \mb_stripos($haystack, $needle, $offset);
10070
            }
10071
10072 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10073
10074 2
            return \mb_stripos($haystack, $needle, $offset, $encoding);
10075
        }
10076
10077 2
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
10078
10079
        if (
10080 2
            $encoding === 'UTF-8' // INFO: "grapheme_stripos()" can't handle other encodings
10081
            &&
10082 2
            $offset >= 0 // grapheme_stripos() can't handle negative offset
10083
            &&
10084 2
            self::$SUPPORT['intl'] === true
10085
        ) {
10086
            $return_tmp = \grapheme_stripos($haystack, $needle, $offset);
10087
            if ($return_tmp !== false) {
10088
                return $return_tmp;
10089
            }
10090
        }
10091
10092
        //
10093
        // fallback for ascii only
10094
        //
10095
10096 2
        if (ASCII::is_ascii($haystack . $needle)) {
10097 2
            return \stripos($haystack, $needle, $offset);
10098
        }
10099
10100
        //
10101
        // fallback via vanilla php
10102
        //
10103
10104 2
        $haystack = self::strtocasefold($haystack, true, false, $encoding, null, false);
10105 2
        $needle = self::strtocasefold($needle, true, false, $encoding, null, false);
10106
10107 2
        return self::strpos($haystack, $needle, $offset, $encoding);
10108
    }
10109
10110
    /**
10111
     * Returns all of haystack starting from and including the first occurrence of needle to the end.
10112
     *
10113
     * EXAMPLE: <code>
10114
     * $str = 'iñtërnâtiônàlizætiøn';
10115
     * $search = 'NÂT';
10116
     *
10117
     * UTF8::stristr($str, $search)); // 'nâtiônàlizætiøn'
10118
     * UTF8::stristr($str, $search, true)); // 'iñtër'
10119
     * </code>
10120
     *
10121
     * @param string $haystack      <p>The input string. Must be valid UTF-8.</p>
10122
     * @param string $needle        <p>The string to look for. Must be valid UTF-8.</p>
10123
     * @param bool   $before_needle [optional] <p>
10124
     *                              If <b>TRUE</b>, it returns the part of the
10125
     *                              haystack before the first occurrence of the needle (excluding the needle).
10126
     *                              </p>
10127
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
10128
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
10129
     *
10130
     * @psalm-pure
10131
     *
10132
     * @return false|string
10133
     *                      <p>A sub-string,<br>or <strong>false</strong> if needle is not found.</p>
10134
     */
10135 13
    public static function stristr(
10136
        string $haystack,
10137
        string $needle,
10138
        bool $before_needle = false,
10139
        string $encoding = 'UTF-8',
10140
        bool $clean_utf8 = false
10141
    ) {
10142 13
        if ($haystack === '') {
10143 3
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
10144
                return '';
10145
            }
10146
10147 3
            return false;
10148
        }
10149
10150 11
        if ($clean_utf8) {
10151
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10152
            // if invalid characters are found in $haystack before $needle
10153 1
            $needle = self::clean($needle);
10154 1
            $haystack = self::clean($haystack);
10155
        }
10156
10157 11
        if ($needle === '') {
10158 2
            if (\PHP_VERSION_ID >= 80000) {
10159
                return $haystack;
10160
            }
10161
10162 2
            return false;
10163
        }
10164
10165 10
        if (self::$SUPPORT['mbstring'] === true) {
10166 10
            if ($encoding === 'UTF-8') {
10167 10
                return \mb_stristr($haystack, $needle, $before_needle);
10168
            }
10169
10170 1
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10171
10172 1
            return \mb_stristr($haystack, $needle, $before_needle, $encoding);
10173
        }
10174
10175
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
10176
10177
        if (
10178
            $encoding !== 'UTF-8'
10179
            &&
10180
            self::$SUPPORT['mbstring'] === false
10181
        ) {
10182
            /**
10183
             * @psalm-suppress ImpureFunctionCall - is is only a warning
10184
             */
10185
            \trigger_error('UTF8::stristr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
10186
        }
10187
10188
        if (
10189
            $encoding === 'UTF-8' // INFO: "grapheme_stristr()" can't handle other encodings
10190
            &&
10191
            self::$SUPPORT['intl'] === true
10192
        ) {
10193
            $return_tmp = \grapheme_stristr($haystack, $needle, $before_needle);
10194
            if ($return_tmp !== false) {
10195
                return $return_tmp;
10196
            }
10197
        }
10198
10199
        if (ASCII::is_ascii($needle . $haystack)) {
10200
            return \stristr($haystack, $needle, $before_needle);
10201
        }
10202
10203
        \preg_match('/^(.*?)' . \preg_quote($needle, '/') . '/usi', $haystack, $match);
10204
10205
        if (!isset($match[1])) {
10206
            return false;
10207
        }
10208
10209
        if ($before_needle) {
10210
            return $match[1];
10211
        }
10212
10213
        return self::substr($haystack, (int) self::strlen($match[1], $encoding), null, $encoding);
10214
    }
10215
10216
    /**
10217
     * Get the string length, not the byte-length!
10218
     *
10219
     * INFO: use UTF8::strwidth() for the char-length
10220
     *
10221
     * EXAMPLE: <code>UTF8::strlen("Iñtërnâtiôn\xE9àlizætiøn")); // 20</code>
10222
     *
10223
     * @see http://php.net/manual/en/function.mb-strlen.php
10224
     *
10225
     * @param string $str        <p>The string being checked for length.</p>
10226
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
10227
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
10228
     *
10229
     * @psalm-pure
10230
     *
10231
     * @return false|int
10232
     *                   <p>
10233
     *                   The number <strong>(int)</strong> of characters in the string $str having character encoding
10234
     *                   $encoding.
10235
     *                   (One multi-byte character counted as +1).
10236
     *                   <br>
10237
     *                   Can return <strong>false</strong>, if e.g. mbstring is not installed and we process invalid
10238
     *                   chars.
10239
     *                   </p>
10240
     */
10241 174
    public static function strlen(
10242
        string $str,
10243
        string $encoding = 'UTF-8',
10244
        bool $clean_utf8 = false
10245
    ) {
10246 174
        if ($str === '') {
10247 21
            return 0;
10248
        }
10249
10250 172
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
10251 12
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10252
        }
10253
10254 172
        if ($clean_utf8) {
10255
            // "mb_strlen" and "\iconv_strlen" returns wrong length,
10256
            // if invalid characters are found in $str
10257 5
            $str = self::clean($str);
10258
        }
10259
10260
        //
10261
        // fallback via mbstring
10262
        //
10263
10264 172
        if (self::$SUPPORT['mbstring'] === true) {
10265 166
            if ($encoding === 'UTF-8') {
10266
                /** @noinspection PhpUsageOfSilenceOperatorInspection - ignore warnings, it's working anyway */
10267 166
                return @\mb_strlen($str);
10268
            }
10269
10270
            /** @noinspection PhpUsageOfSilenceOperatorInspection - ignore warnings, it's working anyway */
10271 4
            return @\mb_strlen($str, $encoding);
10272
        }
10273
10274
        //
10275
        // fallback for binary || ascii only
10276
        //
10277
10278
        if (
10279 8
            $encoding === 'CP850'
10280
            ||
10281 8
            $encoding === 'ASCII'
10282
        ) {
10283
            return \strlen($str);
10284
        }
10285
10286
        if (
10287 8
            $encoding !== 'UTF-8'
10288
            &&
10289 8
            self::$SUPPORT['mbstring'] === false
10290
            &&
10291 8
            self::$SUPPORT['iconv'] === false
10292
        ) {
10293
            /**
10294
             * @psalm-suppress ImpureFunctionCall - is is only a warning
10295
             */
10296 2
            \trigger_error('UTF8::strlen() without mbstring / iconv cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
10297
        }
10298
10299
        //
10300
        // fallback via iconv
10301
        //
10302
10303 8
        if (self::$SUPPORT['iconv'] === true) {
10304
            $return_tmp = \iconv_strlen($str, $encoding);
10305
            if ($return_tmp !== false) {
10306
                return $return_tmp;
10307
            }
10308
        }
10309
10310
        //
10311
        // fallback via intl
10312
        //
10313
10314
        if (
10315 8
            $encoding === 'UTF-8' // INFO: "grapheme_strlen()" can't handle other encodings
10316
            &&
10317 8
            self::$SUPPORT['intl'] === true
10318
        ) {
10319
            $return_tmp = \grapheme_strlen($str);
10320
            if ($return_tmp !== null) {
10321
                return $return_tmp;
10322
            }
10323
        }
10324
10325
        //
10326
        // fallback for ascii only
10327
        //
10328
10329 8
        if (ASCII::is_ascii($str)) {
10330 4
            return \strlen($str);
10331
        }
10332
10333
        //
10334
        // fallback via vanilla php
10335
        //
10336
10337 8
        \preg_match_all('/./us', $str, $parts);
10338
10339 8
        $return_tmp = \count($parts[0]);
10340 8
        if ($return_tmp === 0) {
10341
            return false;
10342
        }
10343
10344 8
        return $return_tmp;
10345
    }
10346
10347
    /**
10348
     * Get string length in byte.
10349
     *
10350
     * @param string $str
10351
     *
10352
     * @psalm-pure
10353
     *
10354
     * @return int
10355
     */
10356 1
    public static function strlen_in_byte(string $str): int
10357
    {
10358 1
        if ($str === '') {
10359
            return 0;
10360
        }
10361
10362 1
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
10363
            // "mb_" is available if overload is used, so use it ...
10364
            return \mb_strlen($str, 'CP850'); // 8-BIT
10365
        }
10366
10367 1
        return \strlen($str);
10368
    }
10369
10370
    /**
10371
     * Case-insensitive string comparisons using a "natural order" algorithm.
10372
     *
10373
     * INFO: natural order version of UTF8::strcasecmp()
10374
     *
10375
     * EXAMPLES: <code>
10376
     * UTF8::strnatcasecmp('2', '10Hello WORLD 中文空白!'); // -1
10377
     * UTF8::strcasecmp('2Hello world 中文空白!', '10Hello WORLD 中文空白!'); // 1
10378
     *
10379
     * UTF8::strnatcasecmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // 1
10380
     * UTF8::strcasecmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // -1
10381
     * </code>
10382
     *
10383
     * @param string $str1     <p>The first string.</p>
10384
     * @param string $str2     <p>The second string.</p>
10385
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
10386
     *
10387
     * @psalm-pure
10388
     *
10389
     * @return int
10390
     *             <strong>&lt; 0</strong> if str1 is less than str2<br>
10391
     *             <strong>&gt; 0</strong> if str1 is greater than str2<br>
10392
     *             <strong>0</strong> if they are equal
10393
     */
10394 2
    public static function strnatcasecmp(string $str1, string $str2, string $encoding = 'UTF-8'): int
10395
    {
10396 2
        return self::strnatcmp(
10397 2
            self::strtocasefold($str1, true, false, $encoding, null, false),
10398 2
            self::strtocasefold($str2, true, false, $encoding, null, false)
10399
        );
10400
    }
10401
10402
    /**
10403
     * String comparisons using a "natural order" algorithm
10404
     *
10405
     * INFO: natural order version of UTF8::strcmp()
10406
     *
10407
     * EXAMPLES: <code>
10408
     * UTF8::strnatcmp('2Hello world 中文空白!', '10Hello WORLD 中文空白!'); // -1
10409
     * UTF8::strcmp('2Hello world 中文空白!', '10Hello WORLD 中文空白!'); // 1
10410
     *
10411
     * UTF8::strnatcmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // 1
10412
     * UTF8::strcmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // -1
10413
     * </code>
10414
     *
10415
     * @see http://php.net/manual/en/function.strnatcmp.php
10416
     *
10417
     * @param string $str1 <p>The first string.</p>
10418
     * @param string $str2 <p>The second string.</p>
10419
     *
10420
     * @psalm-pure
10421
     *
10422
     * @return int
10423
     *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
10424
     *             <strong>&gt; 0</strong> if str1 is greater than str2;<br>
10425
     *             <strong>0</strong> if they are equal
10426
     */
10427 4
    public static function strnatcmp(string $str1, string $str2): int
10428
    {
10429 4
        if ($str1 === $str2) {
10430 4
            return 0;
10431
        }
10432
10433 4
        return \strnatcmp(
10434 4
            (string) self::strtonatfold($str1),
10435 4
            (string) self::strtonatfold($str2)
10436
        );
10437
    }
10438
10439
    /**
10440
     * Case-insensitive string comparison of the first n characters.
10441
     *
10442
     * EXAMPLE: <code>
10443
     * UTF8::strcasecmp("iñtërnâtiôn\nàlizætiøn321", "iñtërnâtiôn\nàlizætiøn123", 5); // 0
10444
     * </code>
10445
     *
10446
     * @see http://php.net/manual/en/function.strncasecmp.php
10447
     *
10448
     * @param string $str1     <p>The first string.</p>
10449
     * @param string $str2     <p>The second string.</p>
10450
     * @param int    $len      <p>The length of strings to be used in the comparison.</p>
10451
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
10452
     *
10453
     * @psalm-pure
10454
     *
10455
     * @return int
10456
     *             <strong>&lt; 0</strong> if <i>str1</i> is less than <i>str2</i>;<br>
10457
     *             <strong>&gt; 0</strong> if <i>str1</i> is greater than <i>str2</i>;<br>
10458
     *             <strong>0</strong> if they are equal
10459
     */
10460 2
    public static function strncasecmp(
10461
        string $str1,
10462
        string $str2,
10463
        int $len,
10464
        string $encoding = 'UTF-8'
10465
    ): int {
10466 2
        return self::strncmp(
10467 2
            self::strtocasefold($str1, true, false, $encoding, null, false),
10468 2
            self::strtocasefold($str2, true, false, $encoding, null, false),
10469 2
            $len
10470
        );
10471
    }
10472
10473
    /**
10474
     * String comparison of the first n characters.
10475
     *
10476
     * EXAMPLE: <code>
10477
     * UTF8::strncmp("Iñtërnâtiôn\nàlizætiøn321", "Iñtërnâtiôn\nàlizætiøn123", 5); // 0
10478
     * </code>
10479
     *
10480
     * @see http://php.net/manual/en/function.strncmp.php
10481
     *
10482
     * @param string $str1     <p>The first string.</p>
10483
     * @param string $str2     <p>The second string.</p>
10484
     * @param int    $len      <p>Number of characters to use in the comparison.</p>
10485
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
10486
     *
10487
     * @psalm-pure
10488
     *
10489
     * @return int
10490
     *             <strong>&lt; 0</strong> if <i>str1</i> is less than <i>str2</i>;<br>
10491
     *             <strong>&gt; 0</strong> if <i>str1</i> is greater than <i>str2</i>;<br>
10492
     *             <strong>0</strong> if they are equal
10493
     */
10494 4
    public static function strncmp(
10495
        string $str1,
10496
        string $str2,
10497
        int $len,
10498
        string $encoding = 'UTF-8'
10499
    ): int {
10500 4
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
10501
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10502
        }
10503
10504 4
        if ($encoding === 'UTF-8') {
10505 4
            $str1 = (string) \mb_substr($str1, 0, $len);
10506 4
            $str2 = (string) \mb_substr($str2, 0, $len);
10507
        } else {
10508
            $str1 = (string) self::substr($str1, 0, $len, $encoding);
10509
            $str2 = (string) self::substr($str2, 0, $len, $encoding);
10510
        }
10511
10512 4
        return self::strcmp($str1, $str2);
10513
    }
10514
10515
    /**
10516
     * Search a string for any of a set of characters.
10517
     *
10518
     * EXAMPLE: <code>UTF8::strpbrk('-中文空白-', '白'); // '白-'</code>
10519
     *
10520
     * @see http://php.net/manual/en/function.strpbrk.php
10521
     *
10522
     * @param string $haystack  <p>The string where char_list is looked for.</p>
10523
     * @param string $char_list <p>This parameter is case-sensitive.</p>
10524
     *
10525
     * @psalm-pure
10526
     *
10527
     * @return false|string
10528
     *                      <p>The string starting from the character found, or false if it is not found.</p>
10529
     */
10530 2
    public static function strpbrk(string $haystack, string $char_list)
10531
    {
10532 2
        if ($haystack === '' || $char_list === '') {
10533 2
            return false;
10534
        }
10535
10536 2
        if (\preg_match('/' . self::rxClass($char_list) . '/us', $haystack, $m)) {
10537 2
            return \substr($haystack, (int) \strpos($haystack, $m[0]));
10538
        }
10539
10540 2
        return false;
10541
    }
10542
10543
    /**
10544
     * Find the position of the first occurrence of a substring in a string.
10545
     *
10546
     * INFO: use UTF8::strpos_in_byte() for the byte-length
10547
     *
10548
     * EXAMPLE: <code>UTF8::strpos('ABC-ÖÄÜ-中文空白-中文空白', '中'); // 8</code>
10549
     *
10550
     * @see http://php.net/manual/en/function.mb-strpos.php
10551
     *
10552
     * @param string     $haystack   <p>The string from which to get the position of the first occurrence of needle.</p>
10553
     * @param int|string $needle     <p>The string to find in haystack.<br>Or a code point as int.</p>
10554
     * @param int        $offset     [optional] <p>The search offset. If it is not specified, 0 is used.</p>
10555
     * @param string     $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
10556
     * @param bool       $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
10557
     *
10558
     * @psalm-pure
10559
     *
10560
     * @return false|int
10561
     *                   The <strong>(int)</strong> numeric position of the first occurrence of needle in the haystack
10562
     *                   string.<br> If needle is not found it returns false.
10563
     */
10564 52
    public static function strpos(
10565
        string $haystack,
10566
        $needle,
10567
        int $offset = 0,
10568
        string $encoding = 'UTF-8',
10569
        bool $clean_utf8 = false
10570
    ) {
10571 52
        if ($haystack === '') {
10572 4
            if (\PHP_VERSION_ID >= 80000) {
10573
                if ($needle === '') {
10574
                    return 0;
10575
                }
10576
            } else {
10577 4
                return false;
10578
            }
10579
        }
10580
10581
        // iconv and mbstring do not support integer $needle
10582 51
        if ((int) $needle === $needle) {
10583
            $needle = (string) self::chr($needle);
10584
        }
10585 51
        $needle = (string) $needle;
10586
10587 51
        if ($haystack === '') {
10588
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
10589
                return 0;
10590
            }
10591
10592
            return false;
10593
        }
10594
10595 51
        if ($needle === '' && \PHP_VERSION_ID < 80000) {
10596 2
            return false;
10597
        }
10598
10599 51
        if ($clean_utf8) {
10600
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10601
            // if invalid characters are found in $haystack before $needle
10602 3
            $needle = self::clean($needle);
10603 3
            $haystack = self::clean($haystack);
10604
        }
10605
10606 51
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
10607 10
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10608
        }
10609
10610
        //
10611
        // fallback via mbstring
10612
        //
10613
10614 51
        if (self::$SUPPORT['mbstring'] === true) {
10615 49
            if ($encoding === 'UTF-8') {
10616
                /** @noinspection PhpUsageOfSilenceOperatorInspection - Offset not contained in string */
10617 49
                return @\mb_strpos($haystack, $needle, $offset);
10618
            }
10619
10620
            /** @noinspection PhpUsageOfSilenceOperatorInspection - Offset not contained in string */
10621 2
            return @\mb_strpos($haystack, $needle, $offset, $encoding);
10622
        }
10623
10624
        //
10625
        // fallback for binary || ascii only
10626
        //
10627
        if (
10628 4
            $encoding === 'CP850'
10629
            ||
10630 4
            $encoding === 'ASCII'
10631
        ) {
10632 2
            return \strpos($haystack, $needle, $offset);
10633
        }
10634
10635
        if (
10636 4
            $encoding !== 'UTF-8'
10637
            &&
10638 4
            self::$SUPPORT['iconv'] === false
10639
            &&
10640 4
            self::$SUPPORT['mbstring'] === false
10641
        ) {
10642
            /**
10643
             * @psalm-suppress ImpureFunctionCall - is is only a warning
10644
             */
10645 2
            \trigger_error('UTF8::strpos() without mbstring / iconv cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
10646
        }
10647
10648
        //
10649
        // fallback via intl
10650
        //
10651
10652
        if (
10653 4
            $encoding === 'UTF-8' // INFO: "grapheme_strpos()" can't handle other encodings
10654
            &&
10655 4
            $offset >= 0 // grapheme_strpos() can't handle negative offset
10656
            &&
10657 4
            self::$SUPPORT['intl'] === true
10658
        ) {
10659
            $return_tmp = \grapheme_strpos($haystack, $needle, $offset);
10660
            if ($return_tmp !== false) {
10661
                return $return_tmp;
10662
            }
10663
        }
10664
10665
        //
10666
        // fallback via iconv
10667
        //
10668
10669
        if (
10670 4
            $offset >= 0 // iconv_strpos() can't handle negative offset
10671
            &&
10672 4
            self::$SUPPORT['iconv'] === true
10673
        ) {
10674
            // ignore invalid negative offset to keep compatibility
10675
            // with php < 5.5.35, < 5.6.21, < 7.0.6
10676
            $return_tmp = \iconv_strpos($haystack, $needle, $offset > 0 ? $offset : 0, $encoding);
10677
            if ($return_tmp !== false) {
10678
                return $return_tmp;
10679
            }
10680
        }
10681
10682
        //
10683
        // fallback for ascii only
10684
        //
10685
10686 4
        if (ASCII::is_ascii($haystack . $needle)) {
10687
            /** @noinspection PhpUsageOfSilenceOperatorInspection - Offset not contained in string */
10688 2
            return @\strpos($haystack, $needle, $offset);
10689
        }
10690
10691
        //
10692
        // fallback via vanilla php
10693
        //
10694
10695 4
        $haystack_tmp = self::substr($haystack, $offset, null, $encoding);
10696 4
        if ($haystack_tmp === false) {
10697
            $haystack_tmp = '';
10698
        }
10699 4
        $haystack = (string) $haystack_tmp;
10700
10701 4
        if ($offset < 0) {
10702
            $offset = 0;
10703
        }
10704
10705 4
        $pos = \strpos($haystack, $needle);
10706 4
        if ($pos === false) {
10707 3
            return false;
10708
        }
10709
10710 4
        if ($pos) {
10711 4
            return $offset + (int) self::strlen(\substr($haystack, 0, $pos), $encoding);
10712
        }
10713
10714 2
        return $offset + 0;
10715
    }
10716
10717
    /**
10718
     * Find the position of the first occurrence of a substring in a string.
10719
     *
10720
     * @param string $haystack <p>
10721
     *                         The string being checked.
10722
     *                         </p>
10723
     * @param string $needle   <p>
10724
     *                         The position counted from the beginning of haystack.
10725
     *                         </p>
10726
     * @param int    $offset   [optional] <p>
10727
     *                         The search offset. If it is not specified, 0 is used.
10728
     *                         </p>
10729
     *
10730
     * @psalm-pure
10731
     *
10732
     * @return false|int
10733
     *                   <p>The numeric position of the first occurrence of needle in the
10734
     *                   haystack string. If needle is not found, it returns false.</p>
10735
     */
10736 2
    public static function strpos_in_byte(string $haystack, string $needle, int $offset = 0)
10737
    {
10738 2
        if ($haystack === '' || $needle === '') {
10739
            return false;
10740
        }
10741
10742 2
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
10743
            // "mb_" is available if overload is used, so use it ...
10744
            return \mb_strpos($haystack, $needle, $offset, 'CP850'); // 8-BIT
10745
        }
10746
10747 2
        return \strpos($haystack, $needle, $offset);
10748
    }
10749
10750
    /**
10751
     * Find the position of the first occurrence of a substring in a string, case-insensitive.
10752
     *
10753
     * @param string $haystack <p>
10754
     *                         The string being checked.
10755
     *                         </p>
10756
     * @param string $needle   <p>
10757
     *                         The position counted from the beginning of haystack.
10758
     *                         </p>
10759
     * @param int    $offset   [optional] <p>
10760
     *                         The search offset. If it is not specified, 0 is used.
10761
     *                         </p>
10762
     *
10763
     * @psalm-pure
10764
     *
10765
     * @return false|int
10766
     *                   <p>The numeric position of the first occurrence of needle in the
10767
     *                   haystack string. If needle is not found, it returns false.</p>
10768
     */
10769 2
    public static function stripos_in_byte(string $haystack, string $needle, int $offset = 0)
10770
    {
10771 2
        if ($haystack === '' || $needle === '') {
10772
            return false;
10773
        }
10774
10775 2
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
10776
            // "mb_" is available if overload is used, so use it ...
10777
            return \mb_stripos($haystack, $needle, $offset, 'CP850'); // 8-BIT
10778
        }
10779
10780 2
        return \stripos($haystack, $needle, $offset);
10781
    }
10782
10783
    /**
10784
     * Find the last occurrence of a character in a string within another.
10785
     *
10786
     * EXAMPLE: <code>UTF8::strrchr('κόσμεκόσμε-äöü', 'κόσμε'); // 'κόσμε-äöü'</code>
10787
     *
10788
     * @see http://php.net/manual/en/function.mb-strrchr.php
10789
     *
10790
     * @param string $haystack      <p>The string from which to get the last occurrence of needle.</p>
10791
     * @param string $needle        <p>The string to find in haystack</p>
10792
     * @param bool   $before_needle [optional] <p>
10793
     *                              Determines which portion of haystack
10794
     *                              this function returns.
10795
     *                              If set to true, it returns all of haystack
10796
     *                              from the beginning to the last occurrence of needle.
10797
     *                              If set to false, it returns all of haystack
10798
     *                              from the last occurrence of needle to the end,
10799
     *                              </p>
10800
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
10801
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
10802
     *
10803
     * @psalm-pure
10804
     *
10805
     * @return false|string
10806
     *                      <p>The portion of haystack or false if needle is not found.</p>
10807
     */
10808 2
    public static function strrchr(
10809
        string $haystack,
10810
        string $needle,
10811
        bool $before_needle = false,
10812
        string $encoding = 'UTF-8',
10813
        bool $clean_utf8 = false
10814
    ) {
10815 2
        if ($haystack === '' || $needle === '') {
10816 2
            return false;
10817
        }
10818
10819 2
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
10820 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10821
        }
10822
10823 2
        if ($clean_utf8) {
10824
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10825
            // if invalid characters are found in $haystack before $needle
10826 2
            $needle = self::clean($needle);
10827 2
            $haystack = self::clean($haystack);
10828
        }
10829
10830
        //
10831
        // fallback via mbstring
10832
        //
10833
10834 2
        if (self::$SUPPORT['mbstring'] === true) {
10835 2
            if ($encoding === 'UTF-8') {
10836 2
                return \mb_strrchr($haystack, $needle, $before_needle);
10837
            }
10838
10839 2
            return \mb_strrchr($haystack, $needle, $before_needle, $encoding);
10840
        }
10841
10842
        //
10843
        // fallback for binary || ascii only
10844
        //
10845
10846
        if (
10847
            !$before_needle
10848
            &&
10849
            (
10850
                $encoding === 'CP850'
10851
                ||
10852
                $encoding === 'ASCII'
10853
            )
10854
        ) {
10855
            return \strrchr($haystack, $needle);
10856
        }
10857
10858
        if (
10859
            $encoding !== 'UTF-8'
10860
            &&
10861
            self::$SUPPORT['mbstring'] === false
10862
        ) {
10863
            /**
10864
             * @psalm-suppress ImpureFunctionCall - is is only a warning
10865
             */
10866
            \trigger_error('UTF8::strrchr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
10867
        }
10868
10869
        //
10870
        // fallback via iconv
10871
        //
10872
10873
        if (self::$SUPPORT['iconv'] === true) {
10874
            $needle_tmp = self::substr($needle, 0, 1, $encoding);
10875
            if ($needle_tmp === false) {
10876
                return false;
10877
            }
10878
            $needle = (string) $needle_tmp;
10879
10880
            $pos = \iconv_strrpos($haystack, $needle, $encoding);
10881
            if ($pos === false) {
10882
                return false;
10883
            }
10884
10885
            if ($before_needle) {
10886
                return self::substr($haystack, 0, $pos, $encoding);
10887
            }
10888
10889
            return self::substr($haystack, $pos, null, $encoding);
10890
        }
10891
10892
        //
10893
        // fallback via vanilla php
10894
        //
10895
10896
        $needle_tmp = self::substr($needle, 0, 1, $encoding);
10897
        if ($needle_tmp === false) {
10898
            return false;
10899
        }
10900
        $needle = (string) $needle_tmp;
10901
10902
        $pos = self::strrpos($haystack, $needle, 0, $encoding);
10903
        if ($pos === false) {
10904
            return false;
10905
        }
10906
10907
        if ($before_needle) {
10908
            return self::substr($haystack, 0, $pos, $encoding);
10909
        }
10910
10911
        return self::substr($haystack, $pos, null, $encoding);
10912
    }
10913
10914
    /**
10915
     * Reverses characters order in the string.
10916
     *
10917
     * EXAMPLE: <code>UTF8::strrev('κ-öäü'); // 'üäö-κ'</code>
10918
     *
10919
     * @param string $str      <p>The input string.</p>
10920
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
10921
     *
10922
     * @psalm-pure
10923
     *
10924
     * @return string
10925
     *                <p>The string with characters in the reverse sequence.</p>
10926
     */
10927 10
    public static function strrev(string $str, string $encoding = 'UTF-8'): string
10928
    {
10929 10
        if ($str === '') {
10930 4
            return '';
10931
        }
10932
10933
        // init
10934 8
        $reversed = '';
10935
10936 8
        $str = self::emoji_encode($str, true);
10937
10938 8
        if ($encoding === 'UTF-8') {
10939 8
            if (self::$SUPPORT['intl'] === true) {
10940
                // try "grapheme" first: https://stackoverflow.com/questions/17496493/strrev-dosent-support-utf-8
10941 8
                $i = (int) \grapheme_strlen($str);
10942 8
                while ($i--) {
10943 8
                    $reversed_tmp = \grapheme_substr($str, $i, 1);
10944 8
                    if ($reversed_tmp !== false) {
10945 8
                        $reversed .= $reversed_tmp;
10946
                    }
10947
                }
10948
            } else {
10949
                $i = (int) \mb_strlen($str);
10950 8
                while ($i--) {
10951
                    $reversed_tmp = \mb_substr($str, $i, 1);
10952
                    if ($reversed_tmp !== false) {
10953
                        $reversed .= $reversed_tmp;
10954
                    }
10955
                }
10956
            }
10957
        } else {
10958
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
10959
10960
            $i = (int) self::strlen($str, $encoding);
10961
            while ($i--) {
10962
                $reversed_tmp = self::substr($str, $i, 1, $encoding);
10963
                if ($reversed_tmp !== false) {
10964
                    $reversed .= $reversed_tmp;
10965
                }
10966
            }
10967
        }
10968
10969 8
        return self::emoji_decode($reversed, true);
10970
    }
10971
10972
    /**
10973
     * Find the last occurrence of a character in a string within another, case-insensitive.
10974
     *
10975
     * EXAMPLE: <code>UTF8::strrichr('Aκόσμεκόσμε-äöü', 'aκόσμε'); // 'Aκόσμεκόσμε-äöü'</code>
10976
     *
10977
     * @see http://php.net/manual/en/function.mb-strrichr.php
10978
     *
10979
     * @param string $haystack      <p>The string from which to get the last occurrence of needle.</p>
10980
     * @param string $needle        <p>The string to find in haystack.</p>
10981
     * @param bool   $before_needle [optional] <p>
10982
     *                              Determines which portion of haystack
10983
     *                              this function returns.
10984
     *                              If set to true, it returns all of haystack
10985
     *                              from the beginning to the last occurrence of needle.
10986
     *                              If set to false, it returns all of haystack
10987
     *                              from the last occurrence of needle to the end,
10988
     *                              </p>
10989
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
10990
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
10991
     *
10992
     * @psalm-pure
10993
     *
10994
     * @return false|string
10995
     *                      <p>The portion of haystack or<br>false if needle is not found.</p>
10996
     */
10997 3
    public static function strrichr(
10998
        string $haystack,
10999
        string $needle,
11000
        bool $before_needle = false,
11001
        string $encoding = 'UTF-8',
11002
        bool $clean_utf8 = false
11003
    ) {
11004 3
        if ($haystack === '' || $needle === '') {
11005 2
            return false;
11006
        }
11007
11008 3
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11009 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11010
        }
11011
11012 3
        if ($clean_utf8) {
11013
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11014
            // if invalid characters are found in $haystack before $needle
11015 2
            $needle = self::clean($needle);
11016 2
            $haystack = self::clean($haystack);
11017
        }
11018
11019
        //
11020
        // fallback via mbstring
11021
        //
11022
11023 3
        if (self::$SUPPORT['mbstring'] === true) {
11024 3
            if ($encoding === 'UTF-8') {
11025 3
                return \mb_strrichr($haystack, $needle, $before_needle);
11026
            }
11027
11028 2
            return \mb_strrichr($haystack, $needle, $before_needle, $encoding);
11029
        }
11030
11031
        //
11032
        // fallback via vanilla php
11033
        //
11034
11035
        $needle_tmp = self::substr($needle, 0, 1, $encoding);
11036
        if ($needle_tmp === false) {
11037
            return false;
11038
        }
11039
        $needle = (string) $needle_tmp;
11040
11041
        $pos = self::strripos($haystack, $needle, 0, $encoding);
11042
        if ($pos === false) {
11043
            return false;
11044
        }
11045
11046
        if ($before_needle) {
11047
            return self::substr($haystack, 0, $pos, $encoding);
11048
        }
11049
11050
        return self::substr($haystack, $pos, null, $encoding);
11051
    }
11052
11053
    /**
11054
     * Find the position of the last occurrence of a substring in a string, case-insensitive.
11055
     *
11056
     * EXAMPLE: <code>UTF8::strripos('ABC-ÖÄÜ-中文空白-中文空白', '中'); // 13</code>
11057
     *
11058
     * @param string     $haystack   <p>The string to look in.</p>
11059
     * @param int|string $needle     <p>The string to look for.</p>
11060
     * @param int        $offset     [optional] <p>Number of characters to ignore in the beginning or end.</p>
11061
     * @param string     $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
11062
     * @param bool       $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
11063
     *
11064
     * @psalm-pure
11065
     *
11066
     * @return false|int
11067
     *                   <p>The <strong>(int)</strong> numeric position of the last occurrence of needle in the haystack
11068
     *                   string.<br>If needle is not found, it returns false.</p>
11069
     */
11070 14
    public static function strripos(
11071
        string $haystack,
11072
        $needle,
11073
        int $offset = 0,
11074
        string $encoding = 'UTF-8',
11075
        bool $clean_utf8 = false
11076
    ) {
11077 14
        if ($haystack === '') {
11078 3
            if (\PHP_VERSION_ID >= 80000) {
11079
                if ($needle === '') {
11080
                    return 0;
11081
                }
11082
            } else {
11083 3
                return false;
11084
            }
11085
        }
11086
11087
        // iconv and mbstring do not support integer $needle
11088 14
        if ((int) $needle === $needle && $needle >= 0) {
11089
            $needle = (string) self::chr($needle);
11090
        }
11091 14
        $needle = (string) $needle;
11092
11093 14
        if ($haystack === '') {
11094
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
11095
                return 0;
11096
            }
11097
11098
            return false;
11099
        }
11100
11101 14
        if ($needle === '' && \PHP_VERSION_ID < 80000) {
11102 3
            return false;
11103
        }
11104
11105 14
        if ($clean_utf8) {
11106
            // mb_strripos() && iconv_strripos() is not tolerant to invalid characters
11107 3
            $needle = self::clean($needle);
11108 3
            $haystack = self::clean($haystack);
11109
        }
11110
11111 14
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11112 9
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11113
        }
11114
11115
        //
11116
        // fallback via mbstrig
11117
        //
11118
11119 14
        if (self::$SUPPORT['mbstring'] === true) {
11120 14
            if ($encoding === 'UTF-8') {
11121 14
                return \mb_strripos($haystack, $needle, $offset);
11122
            }
11123
11124
            return \mb_strripos($haystack, $needle, $offset, $encoding);
11125
        }
11126
11127
        //
11128
        // fallback for binary || ascii only
11129
        //
11130
11131
        if (
11132
            $encoding === 'CP850'
11133
            ||
11134
            $encoding === 'ASCII'
11135
        ) {
11136
            return \strripos($haystack, $needle, $offset);
11137
        }
11138
11139
        if (
11140
            $encoding !== 'UTF-8'
11141
            &&
11142
            self::$SUPPORT['mbstring'] === false
11143
        ) {
11144
            /**
11145
             * @psalm-suppress ImpureFunctionCall - is is only a warning
11146
             */
11147
            \trigger_error('UTF8::strripos() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
11148
        }
11149
11150
        //
11151
        // fallback via intl
11152
        //
11153
11154
        if (
11155
            $encoding === 'UTF-8' // INFO: "grapheme_strripos()" can't handle other encodings
11156
            &&
11157
            $offset >= 0 // grapheme_strripos() can't handle negative offset
11158
            &&
11159
            self::$SUPPORT['intl'] === true
11160
        ) {
11161
            $return_tmp = \grapheme_strripos($haystack, $needle, $offset);
11162
            if ($return_tmp !== false) {
11163
                return $return_tmp;
11164
            }
11165
        }
11166
11167
        //
11168
        // fallback for ascii only
11169
        //
11170
11171
        if (ASCII::is_ascii($haystack . $needle)) {
11172
            return \strripos($haystack, $needle, $offset);
11173
        }
11174
11175
        //
11176
        // fallback via vanilla php
11177
        //
11178
11179
        $haystack = self::strtocasefold($haystack, true, false, $encoding);
11180
        $needle = self::strtocasefold($needle, true, false, $encoding);
11181
11182
        return self::strrpos($haystack, $needle, $offset, $encoding, $clean_utf8);
11183
    }
11184
11185
    /**
11186
     * Finds position of last occurrence of a string within another, case-insensitive.
11187
     *
11188
     * @param string $haystack <p>
11189
     *                         The string from which to get the position of the last occurrence
11190
     *                         of needle.
11191
     *                         </p>
11192
     * @param string $needle   <p>
11193
     *                         The string to find in haystack.
11194
     *                         </p>
11195
     * @param int    $offset   [optional] <p>
11196
     *                         The position in haystack
11197
     *                         to start searching.
11198
     *                         </p>
11199
     *
11200
     * @psalm-pure
11201
     *
11202
     * @return false|int
11203
     *                   <p>eturn the numeric position of the last occurrence of needle in the
11204
     *                   haystack string, or false if needle is not found.</p>
11205
     */
11206 2
    public static function strripos_in_byte(string $haystack, string $needle, int $offset = 0)
11207
    {
11208 2
        if ($haystack === '' || $needle === '') {
11209
            return false;
11210
        }
11211
11212 2
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
11213
            // "mb_" is available if overload is used, so use it ...
11214
            return \mb_strripos($haystack, $needle, $offset, 'CP850'); // 8-BIT
11215
        }
11216
11217 2
        return \strripos($haystack, $needle, $offset);
11218
    }
11219
11220
    /**
11221
     * Find the position of the last occurrence of a substring in a string.
11222
     *
11223
     * EXAMPLE: <code>UTF8::strrpos('ABC-ÖÄÜ-中文空白-中文空白', '中'); // 13</code>
11224
     *
11225
     * @see http://php.net/manual/en/function.mb-strrpos.php
11226
     *
11227
     * @param string     $haystack   <p>The string being checked, for the last occurrence of needle</p>
11228
     * @param int|string $needle     <p>The string to find in haystack.<br>Or a code point as int.</p>
11229
     * @param int        $offset     [optional] <p>May be specified to begin searching an arbitrary number of characters
11230
     *                               into the string. Negative values will stop searching at an arbitrary point prior to
11231
     *                               the end of the string.
11232
     *                               </p>
11233
     * @param string     $encoding   [optional] <p>Set the charset.</p>
11234
     * @param bool       $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
11235
     *
11236
     * @psalm-pure
11237
     *
11238
     * @return false|int
11239
     *                   <p>The <strong>(int)</strong> numeric position of the last occurrence of needle in the haystack
11240
     *                   string.<br>If needle is not found, it returns false.</p>
11241
     */
11242 35
    public static function strrpos(
11243
        string $haystack,
11244
        $needle,
11245
        int $offset = 0,
11246
        string $encoding = 'UTF-8',
11247
        bool $clean_utf8 = false
11248
    ) {
11249 35
        if ($haystack === '') {
11250 4
            if (\PHP_VERSION_ID >= 80000) {
11251
                if ($needle === '') {
11252
                    return 0;
11253
                }
11254
            } else {
11255 4
                return false;
11256
            }
11257
        }
11258
11259
        // iconv and mbstring do not support integer $needle
11260 34
        if ((int) $needle === $needle && $needle >= 0) {
11261 1
            $needle = (string) self::chr($needle);
11262
        }
11263 34
        $needle = (string) $needle;
11264
11265 34
        if ($haystack === '') {
11266
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
11267
                return 0;
11268
            }
11269
11270
            return false;
11271
        }
11272
11273 34
        if ($needle === '' && \PHP_VERSION_ID < 80000) {
11274 2
            return false;
11275
        }
11276
11277 34
        if ($clean_utf8) {
11278
            // mb_strrpos && iconv_strrpos is not tolerant to invalid characters
11279 4
            $needle = self::clean($needle);
11280 4
            $haystack = self::clean($haystack);
11281
        }
11282
11283 34
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11284 8
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11285
        }
11286
11287
        //
11288
        // fallback via mbstring
11289
        //
11290
11291 34
        if (self::$SUPPORT['mbstring'] === true) {
11292 34
            if ($encoding === 'UTF-8') {
11293 34
                return \mb_strrpos($haystack, $needle, $offset);
11294
            }
11295
11296 2
            return \mb_strrpos($haystack, $needle, $offset, $encoding);
11297
        }
11298
11299
        //
11300
        // fallback for binary || ascii only
11301
        //
11302
11303
        if (
11304
            $encoding === 'CP850'
11305
            ||
11306
            $encoding === 'ASCII'
11307
        ) {
11308
            return \strrpos($haystack, $needle, $offset);
11309
        }
11310
11311
        if (
11312
            $encoding !== 'UTF-8'
11313
            &&
11314
            self::$SUPPORT['mbstring'] === false
11315
        ) {
11316
            /**
11317
             * @psalm-suppress ImpureFunctionCall - is is only a warning
11318
             */
11319
            \trigger_error('UTF8::strrpos() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
11320
        }
11321
11322
        //
11323
        // fallback via intl
11324
        //
11325
11326
        if (
11327
            $offset >= 0 // grapheme_strrpos() can't handle negative offset
11328
            &&
11329
            $encoding === 'UTF-8' // INFO: "grapheme_strrpos()" can't handle other encodings
11330
            &&
11331
            self::$SUPPORT['intl'] === true
11332
        ) {
11333
            $return_tmp = \grapheme_strrpos($haystack, $needle, $offset);
11334
            if ($return_tmp !== false) {
11335
                return $return_tmp;
11336
            }
11337
        }
11338
11339
        //
11340
        // fallback for ascii only
11341
        //
11342
11343
        if (ASCII::is_ascii($haystack . $needle)) {
11344
            return \strrpos($haystack, $needle, $offset);
11345
        }
11346
11347
        //
11348
        // fallback via vanilla php
11349
        //
11350
11351
        $haystack_tmp = null;
11352
        if ($offset > 0) {
11353
            $haystack_tmp = self::substr($haystack, $offset);
11354
        } elseif ($offset < 0) {
11355
            $haystack_tmp = self::substr($haystack, 0, $offset);
11356
            $offset = 0;
11357
        }
11358
11359
        if ($haystack_tmp !== null) {
11360
            if ($haystack_tmp === false) {
11361
                $haystack_tmp = '';
11362
            }
11363
            $haystack = (string) $haystack_tmp;
11364
        }
11365
11366
        $pos = \strrpos($haystack, $needle);
11367
        if ($pos === false) {
11368
            return false;
11369
        }
11370
11371
        /** @var false|string $str_tmp - needed for PhpStan (stubs error) */
11372
        $str_tmp = \substr($haystack, 0, $pos);
11373
        if ($str_tmp === false) {
11374
            return false;
11375
        }
11376
11377
        return $offset + (int) self::strlen($str_tmp);
11378
    }
11379
11380
    /**
11381
     * Find the position of the last occurrence of a substring in a string.
11382
     *
11383
     * @param string $haystack <p>
11384
     *                         The string being checked, for the last occurrence
11385
     *                         of needle.
11386
     *                         </p>
11387
     * @param string $needle   <p>
11388
     *                         The string to find in haystack.
11389
     *                         </p>
11390
     * @param int    $offset   [optional] <p>May be specified to begin searching an arbitrary number of characters into
11391
     *                         the string. Negative values will stop searching at an arbitrary point
11392
     *                         prior to the end of the string.
11393
     *                         </p>
11394
     *
11395
     * @psalm-pure
11396
     *
11397
     * @return false|int
11398
     *                   <p>The numeric position of the last occurrence of needle in the
11399
     *                   haystack string. If needle is not found, it returns false.</p>
11400
     */
11401 2
    public static function strrpos_in_byte(string $haystack, string $needle, int $offset = 0)
11402
    {
11403 2
        if ($haystack === '' || $needle === '') {
11404
            return false;
11405
        }
11406
11407 2
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
11408
            // "mb_" is available if overload is used, so use it ...
11409
            return \mb_strrpos($haystack, $needle, $offset, 'CP850'); // 8-BIT
11410
        }
11411
11412 2
        return \strrpos($haystack, $needle, $offset);
11413
    }
11414
11415
    /**
11416
     * Finds the length of the initial segment of a string consisting entirely of characters contained within a given
11417
     * mask.
11418
     *
11419
     * EXAMPLE: <code>UTF8::strspn('iñtërnâtiônàlizætiøn', 'itñ'); // '3'</code>
11420
     *
11421
     * @param string   $str      <p>The input string.</p>
11422
     * @param string   $mask     <p>The mask of chars</p>
11423
     * @param int      $offset   [optional]
11424
     * @param int|null $length   [optional]
11425
     * @param string   $encoding [optional] <p>Set the charset.</p>
11426
     *
11427
     * @psalm-pure
11428
     *
11429
     * @return false|int
11430
     */
11431 10
    public static function strspn(
11432
        string $str,
11433
        string $mask,
11434
        int $offset = 0,
11435
        int $length = null,
11436
        string $encoding = 'UTF-8'
11437
    ) {
11438 10
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11439
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11440
        }
11441
11442 10
        if ($offset || $length !== null) {
11443 2
            if ($encoding === 'UTF-8') {
11444 2
                if ($length === null) {
11445
                    $str = (string) \mb_substr($str, $offset);
11446
                } else {
11447 2
                    $str = (string) \mb_substr($str, $offset, $length);
11448
                }
11449
            } else {
11450
                $str = (string) self::substr($str, $offset, $length, $encoding);
11451
            }
11452
        }
11453
11454 10
        if ($str === '' || $mask === '') {
11455 2
            return 0;
11456
        }
11457
11458 8
        $matches = [];
11459
11460 8
        return \preg_match('/^' . self::rxClass($mask) . '+/u', $str, $matches) ? (int) self::strlen($matches[0], $encoding) : 0;
11461
    }
11462
11463
    /**
11464
     * Returns part of haystack string from the first occurrence of needle to the end of haystack.
11465
     *
11466
     * EXAMPLE: <code>
11467
     * $str = 'iñtërnâtiônàlizætiøn';
11468
     * $search = 'nât';
11469
     *
11470
     * UTF8::strstr($str, $search)); // 'nâtiônàlizætiøn'
11471
     * UTF8::strstr($str, $search, true)); // 'iñtër'
11472
     * </code>
11473
     *
11474
     * @param string $haystack      <p>The input string. Must be valid UTF-8.</p>
11475
     * @param string $needle        <p>The string to look for. Must be valid UTF-8.</p>
11476
     * @param bool   $before_needle [optional] <p>
11477
     *                              If <b>TRUE</b>, strstr() returns the part of the
11478
     *                              haystack before the first occurrence of the needle (excluding the needle).
11479
     *                              </p>
11480
     * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
11481
     * @param bool   $clean_utf8    [optional] <p>Remove non UTF-8 chars from the string.</p>
11482
     *
11483
     * @psalm-pure
11484
     *
11485
     * @return false|string
11486
     *                      <p>A sub-string,<br>or <strong>false</strong> if needle is not found.</p>
11487
     */
11488 3
    public static function strstr(
11489
        string $haystack,
11490
        string $needle,
11491
        bool $before_needle = false,
11492
        string $encoding = 'UTF-8',
11493
        bool $clean_utf8 = false
11494
    ) {
11495 3
        if ($haystack === '') {
11496 2
            if (\PHP_VERSION_ID >= 80000 && $needle === '') {
11497
                return '';
11498
            }
11499
11500 2
            return false;
11501
        }
11502
11503 3
        if ($clean_utf8) {
11504
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11505
            // if invalid characters are found in $haystack before $needle
11506
            $needle = self::clean($needle);
11507
            $haystack = self::clean($haystack);
11508
        }
11509
11510 3
        if ($needle === '') {
11511 1
            if (\PHP_VERSION_ID >= 80000) {
11512
                return $haystack;
11513
            }
11514
11515 1
            return false;
11516
        }
11517
11518 3
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11519 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11520
        }
11521
11522
        //
11523
        // fallback via mbstring
11524
        //
11525
11526 3
        if (self::$SUPPORT['mbstring'] === true) {
11527 3
            if ($encoding === 'UTF-8') {
11528 3
                return \mb_strstr($haystack, $needle, $before_needle);
11529
            }
11530
11531 2
            return \mb_strstr($haystack, $needle, $before_needle, $encoding);
11532
        }
11533
11534
        //
11535
        // fallback for binary || ascii only
11536
        //
11537
11538
        if (
11539
            $encoding === 'CP850'
11540
            ||
11541
            $encoding === 'ASCII'
11542
        ) {
11543
            return \strstr($haystack, $needle, $before_needle);
11544
        }
11545
11546
        if (
11547
            $encoding !== 'UTF-8'
11548
            &&
11549
            self::$SUPPORT['mbstring'] === false
11550
        ) {
11551
            /**
11552
             * @psalm-suppress ImpureFunctionCall - is is only a warning
11553
             */
11554
            \trigger_error('UTF8::strstr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
11555
        }
11556
11557
        //
11558
        // fallback via intl
11559
        //
11560
11561
        if (
11562
            $encoding === 'UTF-8' // INFO: "grapheme_strstr()" can't handle other encodings
11563
            &&
11564
            self::$SUPPORT['intl'] === true
11565
        ) {
11566
            $return_tmp = \grapheme_strstr($haystack, $needle, $before_needle);
11567
            if ($return_tmp !== false) {
11568
                return $return_tmp;
11569
            }
11570
        }
11571
11572
        //
11573
        // fallback for ascii only
11574
        //
11575
11576
        if (ASCII::is_ascii($haystack . $needle)) {
11577
            return \strstr($haystack, $needle, $before_needle);
11578
        }
11579
11580
        //
11581
        // fallback via vanilla php
11582
        //
11583
11584
        \preg_match('/^(.*?)' . \preg_quote($needle, '/') . '/us', $haystack, $match);
11585
11586
        if (!isset($match[1])) {
11587
            return false;
11588
        }
11589
11590
        if ($before_needle) {
11591
            return $match[1];
11592
        }
11593
11594
        return self::substr($haystack, (int) self::strlen($match[1]));
11595
    }
11596
11597
    /**
11598
     * Finds first occurrence of a string within another.
11599
     *
11600
     * @param string $haystack      <p>
11601
     *                              The string from which to get the first occurrence
11602
     *                              of needle.
11603
     *                              </p>
11604
     * @param string $needle        <p>
11605
     *                              The string to find in haystack.
11606
     *                              </p>
11607
     * @param bool   $before_needle [optional] <p>
11608
     *                              Determines which portion of haystack
11609
     *                              this function returns.
11610
     *                              If set to true, it returns all of haystack
11611
     *                              from the beginning to the first occurrence of needle.
11612
     *                              If set to false, it returns all of haystack
11613
     *                              from the first occurrence of needle to the end,
11614
     *                              </p>
11615
     *
11616
     * @psalm-pure
11617
     *
11618
     * @return false|string
11619
     *                      <p>The portion of haystack,
11620
     *                      or false if needle is not found.</p>
11621
     */
11622 2
    public static function strstr_in_byte(
11623
        string $haystack,
11624
        string $needle,
11625
        bool $before_needle = false
11626
    ) {
11627 2
        if ($haystack === '' || $needle === '') {
11628
            return false;
11629
        }
11630
11631 2
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
11632
            // "mb_" is available if overload is used, so use it ...
11633
            return \mb_strstr($haystack, $needle, $before_needle, 'CP850'); // 8-BIT
11634
        }
11635
11636 2
        return \strstr($haystack, $needle, $before_needle);
11637
    }
11638
11639
    /**
11640
     * Unicode transformation for case-less matching.
11641
     *
11642
     * EXAMPLE: <code>UTF8::strtocasefold('ǰ◌̱'); // 'ǰ◌̱'</code>
11643
     *
11644
     * @see http://unicode.org/reports/tr21/tr21-5.html
11645
     *
11646
     * @param string      $str        <p>The input string.</p>
11647
     * @param bool        $full       [optional] <p>
11648
     *                                <b>true</b>, replace full case folding chars (default)<br>
11649
     *                                <b>false</b>, use only limited static array [UTF8::$COMMON_CASE_FOLD]
11650
     *                                </p>
11651
     * @param bool        $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
11652
     * @param string      $encoding   [optional] <p>Set the charset.</p>
11653
     * @param string|null $lang       [optional] <p>Set the language for special cases: az, el, lt, tr</p>
11654
     * @param bool        $lower      [optional] <p>Use lowercase string, otherwise use uppercase string. PS: uppercase
11655
     *                                is for some languages better ...</p>
11656
     *
11657
     * @psalm-pure
11658
     *
11659
     * @return string
11660
     */
11661 32
    public static function strtocasefold(
11662
        string $str,
11663
        bool $full = true,
11664
        bool $clean_utf8 = false,
11665
        string $encoding = 'UTF-8',
11666
        string $lang = null,
11667
        bool $lower = true
11668
    ): string {
11669 32
        if ($str === '') {
11670 5
            return '';
11671
        }
11672
11673 31
        if ($clean_utf8) {
11674
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11675
            // if invalid characters are found in $haystack before $needle
11676 2
            $str = self::clean($str);
11677
        }
11678
11679 31
        $str = self::fixStrCaseHelper($str, $lower, $full);
11680
11681 31
        if ($lang === null && $encoding === 'UTF-8') {
11682 31
            if ($lower) {
11683 2
                return \mb_strtolower($str);
11684
            }
11685
11686 29
            return \mb_strtoupper($str);
11687
        }
11688
11689 2
        if ($lower) {
11690
            return self::strtolower($str, $encoding, false, $lang);
11691
        }
11692
11693 2
        return self::strtoupper($str, $encoding, false, $lang);
11694
    }
11695
11696
    /**
11697
     * Make a string lowercase.
11698
     *
11699
     * EXAMPLE: <code>UTF8::strtolower('DÉJÀ Σσς Iıİi'); // 'déjà σσς iıii'</code>
11700
     *
11701
     * @see http://php.net/manual/en/function.mb-strtolower.php
11702
     *
11703
     * @param string      $str                           <p>The string being lowercased.</p>
11704
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
11705
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
11706
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
11707
     *                                                   tr</p>
11708
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
11709
     *                                                   -> ß</p>
11710
     *
11711
     * @psalm-pure
11712
     *
11713
     * @return string
11714
     *                <p>String with all alphabetic characters converted to lowercase.</p>
11715
     */
11716 73
    public static function strtolower(
11717
        $str,
11718
        string $encoding = 'UTF-8',
11719
        bool $clean_utf8 = false,
11720
        string $lang = null,
11721
        bool $try_to_keep_the_string_length = false
11722
    ): string {
11723
        // init
11724 73
        $str = (string) $str;
11725
11726 73
        if ($str === '') {
11727 1
            return '';
11728
        }
11729
11730 72
        if ($clean_utf8) {
11731
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11732
            // if invalid characters are found in $haystack before $needle
11733 2
            $str = self::clean($str);
11734
        }
11735
11736
        // hack for old php version or for the polyfill ...
11737 72
        if ($try_to_keep_the_string_length) {
11738
            $str = self::fixStrCaseHelper($str, true);
11739
        }
11740
11741 72
        if ($lang === null && $encoding === 'UTF-8') {
11742 13
            return \mb_strtolower($str);
11743
        }
11744
11745 61
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
11746
11747 61
        if ($lang !== null) {
11748 2
            if (self::$SUPPORT['intl'] === true) {
11749 2
                if (self::$INTL_TRANSLITERATOR_LIST === null) {
11750
                    self::$INTL_TRANSLITERATOR_LIST = self::getData('transliterator_list');
11751
                }
11752
11753 2
                $language_code = $lang . '-Lower';
11754 2
                if (!\in_array($language_code, self::$INTL_TRANSLITERATOR_LIST, true)) {
11755
                    /**
11756
                     * @psalm-suppress ImpureFunctionCall - is is only a warning
11757
                     */
11758
                    \trigger_error('UTF8::strtolower() cannot handle special language: ' . $lang . ' | supported: ' . \print_r(self::$INTL_TRANSLITERATOR_LIST, true), \E_USER_WARNING);
11759
11760
                    $language_code = 'Any-Lower';
11761
                }
11762
11763
                /** @noinspection PhpComposerExtensionStubsInspection */
11764
                /** @noinspection UnnecessaryCastingInspection */
11765 2
                return (string) \transliterator_transliterate($language_code, $str);
11766
            }
11767
11768
            /**
11769
             * @psalm-suppress ImpureFunctionCall - is is only a warning
11770
             */
11771
            \trigger_error('UTF8::strtolower() without intl cannot handle the "lang" parameter: ' . $lang, \E_USER_WARNING);
11772
        }
11773
11774
        // always fallback via symfony polyfill
11775 61
        return \mb_strtolower($str, $encoding);
11776
    }
11777
11778
    /**
11779
     * Make a string uppercase.
11780
     *
11781
     * EXAMPLE: <code>UTF8::strtoupper('Déjà Σσς Iıİi'); // 'DÉJÀ ΣΣΣ IIİI'</code>
11782
     *
11783
     * @see http://php.net/manual/en/function.mb-strtoupper.php
11784
     *
11785
     * @param string      $str                           <p>The string being uppercased.</p>
11786
     * @param string      $encoding                      [optional] <p>Set the charset.</p>
11787
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
11788
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
11789
     *                                                   tr</p>
11790
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
11791
     *                                                   -> ß</p>
11792
     *
11793
     * @psalm-pure
11794
     *
11795
     * @return string
11796
     *                <p>String with all alphabetic characters converted to uppercase.</p>
11797
     */
11798 17
    public static function strtoupper(
11799
        $str,
11800
        string $encoding = 'UTF-8',
11801
        bool $clean_utf8 = false,
11802
        string $lang = null,
11803
        bool $try_to_keep_the_string_length = false
11804
    ): string {
11805
        // init
11806 17
        $str = (string) $str;
11807
11808 17
        if ($str === '') {
11809 1
            return '';
11810
        }
11811
11812 16
        if ($clean_utf8) {
11813
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
11814
            // if invalid characters are found in $haystack before $needle
11815 2
            $str = self::clean($str);
11816
        }
11817
11818
        // hack for old php version or for the polyfill ...
11819 16
        if ($try_to_keep_the_string_length) {
11820 2
            $str = self::fixStrCaseHelper($str);
11821
        }
11822
11823 16
        if ($lang === null && $encoding === 'UTF-8') {
11824 8
            return \mb_strtoupper($str);
11825
        }
11826
11827 10
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
11828
11829 10
        if ($lang !== null) {
11830 2
            if (self::$SUPPORT['intl'] === true) {
11831 2
                if (self::$INTL_TRANSLITERATOR_LIST === null) {
11832
                    self::$INTL_TRANSLITERATOR_LIST = self::getData('transliterator_list');
11833
                }
11834
11835 2
                $language_code = $lang . '-Upper';
11836 2
                if (!\in_array($language_code, self::$INTL_TRANSLITERATOR_LIST, true)) {
11837
                    /**
11838
                     * @psalm-suppress ImpureFunctionCall - is is only a warning
11839
                     */
11840
                    \trigger_error('UTF8::strtoupper() without intl for special language: ' . $lang, \E_USER_WARNING);
11841
11842
                    $language_code = 'Any-Upper';
11843
                }
11844
11845
                /** @noinspection PhpComposerExtensionStubsInspection */
11846
                /** @noinspection UnnecessaryCastingInspection */
11847 2
                return (string) \transliterator_transliterate($language_code, $str);
11848
            }
11849
11850
            /**
11851
             * @psalm-suppress ImpureFunctionCall - is is only a warning
11852
             */
11853
            \trigger_error('UTF8::strtolower() without intl cannot handle the "lang"-parameter: ' . $lang, \E_USER_WARNING);
11854
        }
11855
11856
        // always fallback via symfony polyfill
11857 10
        return \mb_strtoupper($str, $encoding);
11858
    }
11859
11860
    /**
11861
     * Translate characters or replace sub-strings.
11862
     *
11863
     * EXAMPLE:
11864
     * <code>
11865
     * $array = [
11866
     *     'Hello'   => '○●◎',
11867
     *     '中文空白' => 'earth',
11868
     * ];
11869
     * UTF8::strtr('Hello 中文空白', $array); // '○●◎ earth'
11870
     * </code>
11871
     *
11872
     * @see http://php.net/manual/en/function.strtr.php
11873
     *
11874
     * @param string          $str  <p>The string being translated.</p>
11875
     * @param string|string[] $from <p>The string replacing from.</p>
11876
     * @param string|string[] $to   [optional] <p>The string being translated to to.</p>
11877
     *
11878
     * @psalm-pure
11879
     *
11880
     * @return string
11881
     *                <p>This function returns a copy of str, translating all occurrences of each character in "from"
11882
     *                to the corresponding character in "to".</p>
11883
     */
11884 2
    public static function strtr(string $str, $from, $to = ''): string
11885
    {
11886 2
        if ($str === '') {
11887
            return '';
11888
        }
11889
11890 2
        if ($from === $to) {
11891
            return $str;
11892
        }
11893
11894 2
        if ($to !== '') {
11895 2
            if (!\is_array($from)) {
11896 2
                $from = self::str_split($from);
11897
            }
11898
11899 2
            if (!\is_array($to)) {
11900 2
                $to = self::str_split($to);
11901
            }
11902
11903 2
            $count_from = \count($from);
11904 2
            $count_to = \count($to);
11905
11906 2
            if ($count_from !== $count_to) {
11907 2
                if ($count_from > $count_to) {
11908 2
                    $from = \array_slice($from, 0, $count_to);
11909 2
                } elseif ($count_from < $count_to) {
11910 2
                    $to = \array_slice($to, 0, $count_from);
11911
                }
11912
            }
11913
11914 2
            $from = \array_combine($from, $to);
11915
            /** @noinspection CallableParameterUseCaseInTypeContextInspection - FP */
11916 2
            if ($from === false) {
11917
                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) . ')');
11918
            }
11919
        }
11920
11921 2
        if (\is_string($from)) {
11922 2
            return \str_replace($from, $to, $str);
0 ignored issues
show
Bug introduced by
It seems like $to can also be of type array<mixed,array> and array<mixed,string[]>; however, parameter $replace of str_replace() does only seem to accept string|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

11922
            return \str_replace($from, /** @scrutinizer ignore-type */ $to, $str);
Loading history...
11923
        }
11924
11925 2
        return \strtr($str, $from);
11926
    }
11927
11928
    /**
11929
     * Return the width of a string.
11930
     *
11931
     * INFO: use UTF8::strlen() for the byte-length
11932
     *
11933
     * EXAMPLE: <code>UTF8::strwidth("Iñtërnâtiôn\xE9àlizætiøn")); // 21</code>
11934
     *
11935
     * @param string $str        <p>The input string.</p>
11936
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
11937
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
11938
     *
11939
     * @psalm-pure
11940
     *
11941
     * @return int
11942
     */
11943 2
    public static function strwidth(
11944
        string $str,
11945
        string $encoding = 'UTF-8',
11946
        bool $clean_utf8 = false
11947
    ): int {
11948 2
        if ($str === '') {
11949 2
            return 0;
11950
        }
11951
11952 2
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
11953 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
11954
        }
11955
11956 2
        if ($clean_utf8) {
11957
            // iconv and mbstring are not tolerant to invalid encoding
11958
            // further, their behaviour is inconsistent with that of PHP's substr
11959 2
            $str = self::clean($str);
11960
        }
11961
11962
        //
11963
        // fallback via mbstring
11964
        //
11965
11966 2
        if (self::$SUPPORT['mbstring'] === true) {
11967 2
            if ($encoding === 'UTF-8') {
11968 2
                return \mb_strwidth($str);
11969
            }
11970
11971
            return \mb_strwidth($str, $encoding);
11972
        }
11973
11974
        //
11975
        // fallback via vanilla php
11976
        //
11977
11978
        if ($encoding !== 'UTF-8') {
11979
            $str = self::encode('UTF-8', $str, false, $encoding);
11980
        }
11981
11982
        $wide = 0;
11983
        $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);
11984
11985
        return ($wide << 1) + (int) self::strlen($str);
11986
    }
11987
11988
    /**
11989
     * Get part of a string.
11990
     *
11991
     * EXAMPLE: <code>UTF8::substr('中文空白', 1, 2); // '文空'</code>
11992
     *
11993
     * @see http://php.net/manual/en/function.mb-substr.php
11994
     *
11995
     * @param string   $str        <p>The string being checked.</p>
11996
     * @param int      $offset     <p>The first position used in str.</p>
11997
     * @param int|null $length     [optional] <p>The maximum length of the returned string.</p>
11998
     * @param string   $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
11999
     * @param bool     $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
12000
     *
12001
     * @psalm-pure
12002
     *
12003
     * @return false|string
12004
     *                      The portion of <i>str</i> specified by the <i>offset</i> and
12005
     *                      <i>length</i> parameters.</p><p>If <i>str</i> is shorter than <i>offset</i>
12006
     *                      characters long, <b>FALSE</b> will be returned.
12007
     */
12008 172
    public static function substr(
12009
        string $str,
12010
        int $offset = 0,
12011
        int $length = null,
12012
        string $encoding = 'UTF-8',
12013
        bool $clean_utf8 = false
12014
    ) {
12015
        // empty string
12016 172
        if ($str === '' || $length === 0) {
12017 8
            return '';
12018
        }
12019
12020 168
        if ($clean_utf8) {
12021
            // iconv and mbstring are not tolerant to invalid encoding
12022
            // further, their behaviour is inconsistent with that of PHP's substr
12023 2
            $str = self::clean($str);
12024
        }
12025
12026
        // whole string
12027 168
        if (!$offset && $length === null) {
12028 7
            return $str;
12029
        }
12030
12031 163
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
12032 19
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
12033
        }
12034
12035
        //
12036
        // fallback via mbstring
12037
        //
12038
12039 163
        if (self::$SUPPORT['mbstring'] === true && $encoding === 'UTF-8') {
12040 161
            if ($length === null) {
12041 64
                return \mb_substr($str, $offset);
12042
            }
12043
12044 102
            return \mb_substr($str, $offset, $length);
12045
        }
12046
12047
        //
12048
        // fallback for binary || ascii only
12049
        //
12050
12051
        if (
12052 4
            $encoding === 'CP850'
12053
            ||
12054 4
            $encoding === 'ASCII'
12055
        ) {
12056
            if ($length === null) {
12057
                return \substr($str, $offset);
12058
            }
12059
12060
            return \substr($str, $offset, $length);
12061
        }
12062
12063
        // otherwise we need the string-length
12064 4
        $str_length = 0;
12065 4
        if ($offset || $length === null) {
12066 4
            $str_length = self::strlen($str, $encoding);
12067
        }
12068
12069
        // e.g.: invalid chars + mbstring not installed
12070 4
        if ($str_length === false) {
12071
            return false;
12072
        }
12073
12074
        // empty string
12075 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...
12076
            return '';
12077
        }
12078
12079
        // impossible
12080 4
        if ($offset && $offset > $str_length) {
12081
            return '';
12082
        }
12083
12084 4
        $length = $length ?? (int) $str_length;
12085
12086
        if (
12087 4
            $encoding !== 'UTF-8'
12088
            &&
12089 4
            self::$SUPPORT['mbstring'] === false
12090
        ) {
12091
            /**
12092
             * @psalm-suppress ImpureFunctionCall - is is only a warning
12093
             */
12094 2
            \trigger_error('UTF8::substr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
12095
        }
12096
12097
        //
12098
        // fallback via intl
12099
        //
12100
12101
        if (
12102 4
            $encoding === 'UTF-8' // INFO: "grapheme_substr()" can't handle other encodings
12103
            &&
12104 4
            $offset >= 0 // grapheme_substr() can't handle negative offset
12105
            &&
12106 4
            self::$SUPPORT['intl'] === true
12107
        ) {
12108
            $return_tmp = \grapheme_substr($str, $offset, $length);
12109
            if ($return_tmp !== false) {
12110
                return $return_tmp;
12111
            }
12112
        }
12113
12114
        //
12115
        // fallback via iconv
12116
        //
12117
12118
        if (
12119 4
            $length >= 0 // "iconv_substr()" can't handle negative length
12120
            &&
12121 4
            self::$SUPPORT['iconv'] === true
12122
        ) {
12123
            $return_tmp = \iconv_substr($str, $offset, $length);
12124
            if ($return_tmp !== false) {
12125
                return $return_tmp;
12126
            }
12127
        }
12128
12129
        //
12130
        // fallback for ascii only
12131
        //
12132
12133 4
        if (ASCII::is_ascii($str)) {
12134
            return \substr($str, $offset, $length);
12135
        }
12136
12137
        //
12138
        // fallback via vanilla php
12139
        //
12140
12141
        // split to array, and remove invalid characters
12142 4
        $array = self::str_split($str);
12143
12144
        // extract relevant part, and join to make sting again
12145 4
        return \implode('', \array_slice($array, $offset, $length));
12146
    }
12147
12148
    /**
12149
     * Binary-safe comparison of two strings from an offset, up to a length of characters.
12150
     *
12151
     * EXAMPLE: <code>
12152
     * UTF8::substr_compare("○●◎\r", '●◎', 0, 2); // -1
12153
     * UTF8::substr_compare("○●◎\r", '◎●', 1, 2); // 1
12154
     * UTF8::substr_compare("○●◎\r", '●◎', 1, 2); // 0
12155
     * </code>
12156
     *
12157
     * @param string   $str1               <p>The main string being compared.</p>
12158
     * @param string   $str2               <p>The secondary string being compared.</p>
12159
     * @param int      $offset             [optional] <p>The start position for the comparison. If negative, it starts
12160
     *                                     counting from the end of the string.</p>
12161
     * @param int|null $length             [optional] <p>The length of the comparison. The default value is the largest
12162
     *                                     of the length of the str compared to the length of main_str less the
12163
     *                                     offset.</p>
12164
     * @param bool     $case_insensitivity [optional] <p>If case_insensitivity is TRUE, comparison is case
12165
     *                                     insensitive.</p>
12166
     * @param string   $encoding           [optional] <p>Set the charset for e.g. "mb_" function</p>
12167
     *
12168
     * @psalm-pure
12169
     *
12170
     * @return int
12171
     *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
12172
     *             <strong>&gt; 0</strong> if str1 is greater than str2,<br>
12173
     *             <strong>0</strong> if they are equal
12174
     */
12175 2
    public static function substr_compare(
12176
        string $str1,
12177
        string $str2,
12178
        int $offset = 0,
12179
        int $length = null,
12180
        bool $case_insensitivity = false,
12181
        string $encoding = 'UTF-8'
12182
    ): int {
12183
        if (
12184 2
            $offset !== 0
12185
            ||
12186 2
            $length !== null
12187
        ) {
12188 2
            if ($encoding === 'UTF-8') {
12189 2
                if ($length === null) {
12190 2
                    $str1 = (string) \mb_substr($str1, $offset);
12191
                } else {
12192 2
                    $str1 = (string) \mb_substr($str1, $offset, $length);
12193
                }
12194 2
                $str2 = (string) \mb_substr($str2, 0, (int) self::strlen($str1));
12195
            } else {
12196
                $encoding = self::normalize_encoding($encoding, 'UTF-8');
12197
12198
                $str1 = (string) self::substr($str1, $offset, $length, $encoding);
12199
                $str2 = (string) self::substr($str2, 0, (int) self::strlen($str1), $encoding);
12200
            }
12201
        }
12202
12203 2
        if ($case_insensitivity) {
12204 2
            return self::strcasecmp($str1, $str2, $encoding);
12205
        }
12206
12207 2
        return self::strcmp($str1, $str2);
12208
    }
12209
12210
    /**
12211
     * Count the number of substring occurrences.
12212
     *
12213
     * EXAMPLE: <code>UTF8::substr_count('中文空白', '文空', 1, 2); // 1</code>
12214
     *
12215
     * @see http://php.net/manual/en/function.substr-count.php
12216
     *
12217
     * @param string   $haystack   <p>The string to search in.</p>
12218
     * @param string   $needle     <p>The substring to search for.</p>
12219
     * @param int      $offset     [optional] <p>The offset where to start counting.</p>
12220
     * @param int|null $length     [optional] <p>
12221
     *                             The maximum length after the specified offset to search for the
12222
     *                             substring. It outputs a warning if the offset plus the length is
12223
     *                             greater than the haystack length.
12224
     *                             </p>
12225
     * @param string   $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
12226
     * @param bool     $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
12227
     *
12228
     * @psalm-pure
12229
     *
12230
     * @return false|int
12231
     *                   <p>This functions returns an integer or false if there isn't a string.</p>
12232
     */
12233 5
    public static function substr_count(
12234
        string $haystack,
12235
        string $needle,
12236
        int $offset = 0,
12237
        int $length = null,
12238
        string $encoding = 'UTF-8',
12239
        bool $clean_utf8 = false
12240
    ) {
12241 5
        if ($needle === '') {
12242 2
            return false;
12243
        }
12244
12245 5
        if ($haystack === '') {
12246 2
            if (\PHP_VERSION_ID >= 80000) {
12247
                return 0;
12248
            }
12249
12250 2
            return 0;
12251
        }
12252
12253 5
        if ($length === 0) {
12254 2
            return 0;
12255
        }
12256
12257 5
        if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
12258 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
12259
        }
12260
12261 5
        if ($clean_utf8) {
12262
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
12263
            // if invalid characters are found in $haystack before $needle
12264
            $needle = self::clean($needle);
12265
            $haystack = self::clean($haystack);
12266
        }
12267
12268 5
        if ($offset || $length > 0) {
12269 2
            if ($length === null) {
12270 2
                $length_tmp = self::strlen($haystack, $encoding);
12271 2
                if ($length_tmp === false) {
12272
                    return false;
12273
                }
12274 2
                $length = (int) $length_tmp;
12275
            }
12276
12277 2
            if ($encoding === 'UTF-8') {
12278 2
                $haystack = (string) \mb_substr($haystack, $offset, $length);
12279
            } else {
12280 2
                $haystack = (string) \mb_substr($haystack, $offset, $length, $encoding);
12281
            }
12282
        }
12283
12284
        if (
12285 5
            $encoding !== 'UTF-8'
12286
            &&
12287 5
            self::$SUPPORT['mbstring'] === false
12288
        ) {
12289
            /**
12290
             * @psalm-suppress ImpureFunctionCall - is is only a warning
12291
             */
12292
            \trigger_error('UTF8::substr_count() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
12293
        }
12294
12295 5
        if (self::$SUPPORT['mbstring'] === true) {
12296 5
            if ($encoding === 'UTF-8') {
12297 5
                return \mb_substr_count($haystack, $needle);
12298
            }
12299
12300 2
            return \mb_substr_count($haystack, $needle, $encoding);
12301
        }
12302
12303
        \preg_match_all('/' . \preg_quote($needle, '/') . '/us', $haystack, $matches, \PREG_SET_ORDER);
12304
12305
        return \count($matches);
12306
    }
12307
12308
    /**
12309
     * Count the number of substring occurrences.
12310
     *
12311
     * @param string   $haystack <p>
12312
     *                           The string being checked.
12313
     *                           </p>
12314
     * @param string   $needle   <p>
12315
     *                           The string being found.
12316
     *                           </p>
12317
     * @param int      $offset   [optional] <p>
12318
     *                           The offset where to start counting
12319
     *                           </p>
12320
     * @param int|null $length   [optional] <p>
12321
     *                           The maximum length after the specified offset to search for the
12322
     *                           substring. It outputs a warning if the offset plus the length is
12323
     *                           greater than the haystack length.
12324
     *                           </p>
12325
     *
12326
     * @psalm-pure
12327
     *
12328
     * @return false|int
12329
     *                   <p>The number of times the
12330
     *                   needle substring occurs in the
12331
     *                   haystack string.</p>
12332
     */
12333 4
    public static function substr_count_in_byte(
12334
        string $haystack,
12335
        string $needle,
12336
        int $offset = 0,
12337
        int $length = null
12338
    ) {
12339 4
        if ($haystack === '' || $needle === '') {
12340 1
            return 0;
12341
        }
12342
12343
        if (
12344 3
            ($offset || $length !== null)
12345
            &&
12346 3
            self::$SUPPORT['mbstring_func_overload'] === true
12347
        ) {
12348
            if ($length === null) {
12349
                $length_tmp = self::strlen($haystack);
12350
                if ($length_tmp === false) {
12351
                    return false;
12352
                }
12353
                $length = (int) $length_tmp;
12354
            }
12355
12356
            if (
12357
                (
12358
                    $length !== 0
12359
                    &&
12360
                    $offset !== 0
12361
                )
12362
                &&
12363
                ($length + $offset) <= 0
12364
                &&
12365
                \PHP_VERSION_ID < 71000 // output from "substr_count()" have changed in PHP 7.1
12366
            ) {
12367
                return false;
12368
            }
12369
12370
            /** @var false|string $haystack_tmp - needed for PhpStan (stubs error) */
12371
            $haystack_tmp = \substr($haystack, $offset, $length);
12372
            if ($haystack_tmp === false) {
12373
                $haystack_tmp = '';
12374
            }
12375
            $haystack = (string) $haystack_tmp;
12376
        }
12377
12378 3
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
12379
            // "mb_" is available if overload is used, so use it ...
12380
            return \mb_substr_count($haystack, $needle, 'CP850'); // 8-BIT
12381
        }
12382
12383 3
        if ($length === null) {
12384 3
            return \substr_count($haystack, $needle, $offset);
12385
        }
12386
12387
        return \substr_count($haystack, $needle, $offset, $length);
12388
    }
12389
12390
    /**
12391
     * Returns the number of occurrences of $substring in the given string.
12392
     * By default, the comparison is case-sensitive, but can be made insensitive
12393
     * by setting $case_sensitive to false.
12394
     *
12395
     * @param string $str            <p>The input string.</p>
12396
     * @param string $substring      <p>The substring to search for.</p>
12397
     * @param bool   $case_sensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
12398
     * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
12399
     *
12400
     * @psalm-pure
12401
     *
12402
     * @return int
12403
     */
12404 15
    public static function substr_count_simple(
12405
        string $str,
12406
        string $substring,
12407
        bool $case_sensitive = true,
12408
        string $encoding = 'UTF-8'
12409
    ): int {
12410 15
        if ($str === '' || $substring === '') {
12411 2
            return 0;
12412
        }
12413
12414 13
        if ($encoding === 'UTF-8') {
12415 7
            if ($case_sensitive) {
12416
                return (int) \mb_substr_count($str, $substring);
12417
            }
12418
12419 7
            return (int) \mb_substr_count(
12420 7
                \mb_strtoupper($str),
12421 7
                \mb_strtoupper($substring)
12422
            );
12423
        }
12424
12425 6
        $encoding = self::normalize_encoding($encoding, 'UTF-8');
12426
12427 6
        if ($case_sensitive) {
12428 3
            return (int) \mb_substr_count($str, $substring, $encoding);
12429
        }
12430
12431 3
        return (int) \mb_substr_count(
12432 3
            self::strtocasefold($str, true, false, $encoding, null, false),
12433 3
            self::strtocasefold($substring, true, false, $encoding, null, false),
12434 3
            $encoding
12435
        );
12436
    }
12437
12438
    /**
12439
     * Removes a prefix ($needle) from the beginning of the string ($haystack), case-insensitive.
12440
     *
12441
     * EXMAPLE: <code>
12442
     * UTF8::substr_ileft('ΚόσμεMiddleEnd', 'Κόσμε'); // 'MiddleEnd'
12443
     * UTF8::substr_ileft('ΚόσμεMiddleEnd', 'κόσμε'); // 'MiddleEnd'
12444
     * </code>
12445
     *
12446
     * @param string $haystack <p>The string to search in.</p>
12447
     * @param string $needle   <p>The substring to search for.</p>
12448
     *
12449
     * @psalm-pure
12450
     *
12451
     * @return string
12452
     *                <p>Return the sub-string.</p>
12453
     */
12454 2
    public static function substr_ileft(string $haystack, string $needle): string
12455
    {
12456 2
        if ($haystack === '') {
12457 2
            return '';
12458
        }
12459
12460 2
        if ($needle === '') {
12461 2
            return $haystack;
12462
        }
12463
12464 2
        if (self::str_istarts_with($haystack, $needle)) {
12465 2
            $haystack = (string) \mb_substr($haystack, (int) self::strlen($needle));
12466
        }
12467
12468 2
        return $haystack;
12469
    }
12470
12471
    /**
12472
     * Get part of a string process in bytes.
12473
     *
12474
     * @param string   $str    <p>The string being checked.</p>
12475
     * @param int      $offset <p>The first position used in str.</p>
12476
     * @param int|null $length [optional] <p>The maximum length of the returned string.</p>
12477
     *
12478
     * @psalm-pure
12479
     *
12480
     * @return false|string
12481
     *                      The portion of <i>str</i> specified by the <i>offset</i> and
12482
     *                      <i>length</i> parameters.</p><p>If <i>str</i> is shorter than <i>offset</i>
12483
     *                      characters long, <b>FALSE</b> will be returned.
12484
     */
12485 1
    public static function substr_in_byte(string $str, int $offset = 0, int $length = null)
12486
    {
12487
        // empty string
12488 1
        if ($str === '' || $length === 0) {
12489
            return '';
12490
        }
12491
12492
        // whole string
12493 1
        if (!$offset && $length === null) {
12494
            return $str;
12495
        }
12496
12497 1
        if (self::$SUPPORT['mbstring_func_overload'] === true) {
12498
            // "mb_" is available if overload is used, so use it ...
12499
            return \mb_substr($str, $offset, $length, 'CP850'); // 8-BIT
12500
        }
12501
12502 1
        return \substr($str, $offset, $length ?? 2147483647);
12503
    }
12504
12505
    /**
12506
     * Removes a suffix ($needle) from the end of the string ($haystack), case-insensitive.
12507
     *
12508
     * EXAMPLE: <code>
12509
     * UTF8::substr_iright('BeginMiddleΚόσμε', 'Κόσμε'); // 'BeginMiddle'
12510
     * UTF8::substr_iright('BeginMiddleΚόσμε', 'κόσμε'); // 'BeginMiddle'
12511
     * </code>
12512
     *
12513
     * @param string $haystack <p>The string to search in.</p>
12514
     * @param string $needle   <p>The substring to search for.</p>
12515
     *
12516
     * @psalm-pure
12517
     *
12518
     * @return string
12519
     *                <p>Return the sub-string.<p>
12520
     */
12521 2
    public static function substr_iright(string $haystack, string $needle): string
12522
    {
12523 2
        if ($haystack === '') {
12524 2
            return '';
12525
        }
12526
12527 2
        if ($needle === '') {
12528 2
            return $haystack;
12529
        }
12530
12531 2
        if (self::str_iends_with($haystack, $needle)) {
12532 2
            $haystack = (string) \mb_substr($haystack, 0, (int) self::strlen($haystack) - (int) self::strlen($needle));
12533
        }
12534
12535 2
        return $haystack;
12536
    }
12537
12538
    /**
12539
     * Removes a prefix ($needle) from the beginning of the string ($haystack).
12540
     *
12541
     * EXAMPLE: <code>
12542
     * UTF8::substr_left('ΚόσμεMiddleEnd', 'Κόσμε'); // 'MiddleEnd'
12543
     * UTF8::substr_left('ΚόσμεMiddleEnd', 'κόσμε'); // 'ΚόσμεMiddleEnd'
12544
     * </code>
12545
     *
12546
     * @param string $haystack <p>The string to search in.</p>
12547
     * @param string $needle   <p>The substring to search for.</p>
12548
     *
12549
     * @psalm-pure
12550
     *
12551
     * @return string
12552
     *                <p>Return the sub-string.</p>
12553
     */
12554 2
    public static function substr_left(string $haystack, string $needle): string
12555
    {
12556 2
        if ($haystack === '') {
12557 2
            return '';
12558
        }
12559
12560 2
        if ($needle === '') {
12561 2
            return $haystack;
12562
        }
12563
12564 2
        if (self::str_starts_with($haystack, $needle)) {
12565 2
            $haystack = (string) \mb_substr($haystack, (int) self::strlen($needle));
12566
        }
12567
12568 2
        return $haystack;
12569
    }
12570
12571
    /**
12572
     * Replace text within a portion of a string.
12573
     *
12574
     * EXAMPLE: <code>UTF8::substr_replace(array('Iñtërnâtiônàlizætiøn', 'foo'), 'æ', 1); // array('Iæñtërnâtiônàlizætiøn', 'fæoo')</code>
12575
     *
12576
     * source: https://gist.github.com/stemar/8287074
12577
     *
12578
     * @param string|string[] $str         <p>The input string or an array of stings.</p>
12579
     * @param string|string[] $replacement <p>The replacement string or an array of stings.</p>
12580
     * @param int|int[]       $offset      <p>
12581
     *                                     If start is positive, the replacing will begin at the start'th offset
12582
     *                                     into string.
12583
     *                                     <br><br>
12584
     *                                     If start is negative, the replacing will begin at the start'th character
12585
     *                                     from the end of string.
12586
     *                                     </p>
12587
     * @param int|int[]|null  $length      [optional] <p>If given and is positive, it represents the length of the
12588
     *                                     portion of string which is to be replaced. If it is negative, it
12589
     *                                     represents the number of characters from the end of string at which to
12590
     *                                     stop replacing. If it is not given, then it will default to strlen(
12591
     *                                     string ); i.e. end the replacing at the end of string. Of course, if
12592
     *                                     length is zero then this function will have the effect of inserting
12593
     *                                     replacement into string at the given start offset.</p>
12594
     * @param string          $encoding    [optional] <p>Set the charset for e.g. "mb_" function</p>
12595
     *
12596
     * @psalm-pure
12597
     *
12598
     * @return string|string[]
12599
     *                         <p>The result string is returned. If string is an array then array is returned.</p>
12600
     */
12601 10
    public static function substr_replace(
12602
        $str,
12603
        $replacement,
12604
        $offset,
12605
        $length = null,
12606
        string $encoding = 'UTF-8'
12607
    ) {
12608 10
        if (\is_array($str)) {
12609 1
            $num = \count($str);
12610
12611
            // the replacement
12612 1
            if (\is_array($replacement)) {
12613 1
                $replacement = \array_slice($replacement, 0, $num);
12614
            } else {
12615 1
                $replacement = \array_pad([$replacement], $num, $replacement);
12616
            }
12617
12618
            // the offset
12619 1
            if (\is_array($offset)) {
12620 1
                $offset = \array_slice($offset, 0, $num);
12621 1
                foreach ($offset as &$value_tmp) {
12622 1
                    $value_tmp = (int) $value_tmp === $value_tmp ? $value_tmp : 0;
12623
                }
12624 1
                unset($value_tmp);
12625
            } else {
12626 1
                $offset = \array_pad([$offset], $num, $offset);
12627
            }
12628
12629
            // the length
12630 1
            if ($length === null) {
12631 1
                $length = \array_fill(0, $num, 0);
12632 1
            } elseif (\is_array($length)) {
12633 1
                $length = \array_slice($length, 0, $num);
12634 1
                foreach ($length as &$value_tmp_V2) {
12635 1
                    $value_tmp_V2 = (int) $value_tmp_V2 === $value_tmp_V2 ? $value_tmp_V2 : $num;
12636
                }
12637 1
                unset($value_tmp_V2);
12638
            } else {
12639 1
                $length = \array_pad([$length], $num, $length);
12640
            }
12641
12642
            // recursive call
12643 1
            return \array_map([self::class, 'substr_replace'], $str, $replacement, $offset, $length);
12644
        }
12645
12646 10
        if (\is_array($replacement)) {
12647 1
            if ($replacement !== []) {
12648 1
                $replacement = $replacement[0];
12649
            } else {
12650 1
                $replacement = '';
12651
            }
12652
        }
12653
12654
        // init
12655 10
        $str = (string) $str;
12656 10
        $replacement = (string) $replacement;
12657
12658 10
        if (\is_array($length)) {
12659
            throw new \InvalidArgumentException('Parameter "$length" can only be an array, if "$str" is also an array.');
12660
        }
12661
12662 10
        if (\is_array($offset)) {
12663
            throw new \InvalidArgumentException('Parameter "$offset" can only be an array, if "$str" is also an array.');
12664
        }
12665
12666 10
        if ($str === '') {
12667 1
            return $replacement;
12668
        }
12669
12670 9
        if (self::$SUPPORT['mbstring'] === true) {
12671 9
            $string_length = (int) self::strlen($str, $encoding);
12672
12673 9
            if ($offset < 0) {
12674 1
                $offset = (int) \max(0, $string_length + $offset);
12675 9
            } elseif ($offset > $string_length) {
12676 1
                $offset = $string_length;
12677
            }
12678
12679 9
            if ($length !== null && $length < 0) {
12680 1
                $length = (int) \max(0, $string_length - $offset + $length);
12681 9
            } elseif ($length === null || $length > $string_length) {
12682 4
                $length = $string_length;
12683
            }
12684
12685
            /** @noinspection AdditionOperationOnArraysInspection */
12686 9
            if (($offset + $length) > $string_length) {
12687 4
                $length = $string_length - $offset;
12688
            }
12689
12690
            /** @noinspection AdditionOperationOnArraysInspection */
12691 9
            return ((string) \mb_substr($str, 0, $offset, $encoding)) .
12692 9
                   $replacement .
12693 9
                   ((string) \mb_substr($str, $offset + $length, $string_length - $offset - $length, $encoding));
12694
        }
12695
12696
        //
12697
        // fallback for ascii only
12698
        //
12699
12700
        if (ASCII::is_ascii($str)) {
12701
            return ($length === null) ?
12702
                \substr_replace($str, $replacement, $offset) :
12703
                \substr_replace($str, $replacement, $offset, $length);
12704
        }
12705
12706
        //
12707
        // fallback via vanilla php
12708
        //
12709
12710
        \preg_match_all('/./us', $str, $str_matches);
12711
        \preg_match_all('/./us', $replacement, $replacement_matches);
12712
12713
        if ($length === null) {
12714
            $length_tmp = self::strlen($str, $encoding);
12715
            if ($length_tmp === false) {
12716
                // e.g.: non mbstring support + invalid chars
12717
                return '';
12718
            }
12719
            $length = (int) $length_tmp;
12720
        }
12721
12722
        \array_splice($str_matches[0], $offset, $length, $replacement_matches[0]);
12723
12724
        return \implode('', $str_matches[0]);
12725
    }
12726
12727
    /**
12728
     * Removes a suffix ($needle) from the end of the string ($haystack).
12729
     *
12730
     * EXAMPLE: <code>
12731
     * UTF8::substr_right('BeginMiddleΚόσμε', 'Κόσμε'); // 'BeginMiddle'
12732
     * UTF8::substr_right('BeginMiddleΚόσμε', 'κόσμε'); // 'BeginMiddleΚόσμε'
12733
     * </code>
12734
     *
12735
     * @param string $haystack <p>The string to search in.</p>
12736
     * @param string $needle   <p>The substring to search for.</p>
12737
     * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
12738
     *
12739
     * @psalm-pure
12740
     *
12741
     * @return string
12742
     *                <p>Return the sub-string.</p>
12743
     */
12744 2
    public static function substr_right(
12745
        string $haystack,
12746
        string $needle,
12747
        string $encoding = 'UTF-8'
12748
    ): string {
12749 2
        if ($haystack === '') {
12750 2
            return '';
12751
        }
12752
12753 2
        if ($needle === '') {
12754 2
            return $haystack;
12755
        }
12756
12757
        if (
12758 2
            $encoding === 'UTF-8'
12759
            &&
12760 2
            \substr($haystack, -\strlen($needle)) === $needle
12761
        ) {
12762 2
            return (string) \mb_substr($haystack, 0, (int) \mb_strlen($haystack) - (int) \mb_strlen($needle));
12763
        }
12764
12765 2
        if (\substr($haystack, -\strlen($needle)) === $needle) {
12766
            return (string) self::substr(
12767
                $haystack,
12768
                0,
12769
                (int) self::strlen($haystack, $encoding) - (int) self::strlen($needle, $encoding),
12770
                $encoding
12771
            );
12772
        }
12773
12774 2
        return $haystack;
12775
    }
12776
12777
    /**
12778
     * Returns a case swapped version of the string.
12779
     *
12780
     * EXAMPLE: <code>UTF8::swapCase('déJÀ σσς iıII'); // 'DÉjà ΣΣΣ IIii'</code>
12781
     *
12782
     * @param string $str        <p>The input string.</p>
12783
     * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
12784
     * @param bool   $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
12785
     *
12786
     * @psalm-pure
12787
     *
12788
     * @return string
12789
     *                <p>Each character's case swapped.</p>
12790
     */
12791 6
    public static function swapCase(string $str, string $encoding = 'UTF-8', bool $clean_utf8 = false): string
12792
    {
12793 6
        if ($str === '') {
12794 1
            return '';
12795
        }
12796
12797 6
        if ($clean_utf8) {
12798
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
12799
            // if invalid characters are found in $haystack before $needle
12800 2
            $str = self::clean($str);
12801
        }
12802
12803 6
        if ($encoding === 'UTF-8') {
12804 4
            return (string) (\mb_strtolower($str) ^ \mb_strtoupper($str) ^ $str);
12805
        }
12806
12807 4
        return (string) (self::strtolower($str, $encoding) ^ self::strtoupper($str, $encoding) ^ $str);
12808
    }
12809
12810
    /**
12811
     * Checks whether symfony-polyfills are used.
12812
     *
12813
     * @psalm-pure
12814
     *
12815
     * @return bool
12816
     *              <p><strong>true</strong> if in use, <strong>false</strong> otherwise</p>
12817
     *
12818
     * @internal <p>Please do not use it anymore, we will make is private in next major version.</p>
12819
     */
12820
    public static function symfony_polyfill_used(): bool
12821
    {
12822
        // init
12823
        $return = false;
12824
12825
        $return_tmp = \extension_loaded('mbstring');
12826
        if (!$return_tmp && \function_exists('mb_strlen')) {
12827
            $return = true;
12828
        }
12829
12830
        $return_tmp = \extension_loaded('iconv');
12831
        if (!$return_tmp && \function_exists('iconv')) {
12832
            $return = true;
12833
        }
12834
12835
        return $return;
12836
    }
12837
12838
    /**
12839
     * @param string $str
12840
     * @param int    $tab_length
12841
     *
12842
     * @psalm-pure
12843
     *
12844
     * @return string
12845
     */
12846 6
    public static function tabs_to_spaces(string $str, int $tab_length = 4): string
12847
    {
12848 6
        if ($tab_length === 4) {
12849 3
            $spaces = '    ';
12850 3
        } elseif ($tab_length === 2) {
12851 1
            $spaces = '  ';
12852
        } else {
12853 2
            $spaces = \str_repeat(' ', $tab_length);
12854
        }
12855
12856 6
        return \str_replace("\t", $spaces, $str);
12857
    }
12858
12859
    /**
12860
     * Converts the first character of each word in the string to uppercase
12861
     * and all other chars to lowercase.
12862
     *
12863
     * @param string      $str                           <p>The input string.</p>
12864
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
12865
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
12866
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
12867
     *                                                   tr</p>
12868
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
12869
     *                                                   -> ß</p>
12870
     *
12871
     * @psalm-pure
12872
     *
12873
     * @return string
12874
     *                <p>A string with all characters of $str being title-cased.</p>
12875
     */
12876 5
    public static function titlecase(
12877
        string $str,
12878
        string $encoding = 'UTF-8',
12879
        bool $clean_utf8 = false,
12880
        string $lang = null,
12881
        bool $try_to_keep_the_string_length = false
12882
    ): string {
12883 5
        if ($clean_utf8) {
12884
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
12885
            // if invalid characters are found in $haystack before $needle
12886
            $str = self::clean($str);
12887
        }
12888
12889
        if (
12890 5
            $lang === null
12891
            &&
12892 5
            !$try_to_keep_the_string_length
12893
        ) {
12894 5
            if ($encoding === 'UTF-8') {
12895 3
                return \mb_convert_case($str, \MB_CASE_TITLE);
12896
            }
12897
12898 2
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
12899
12900 2
            return \mb_convert_case($str, \MB_CASE_TITLE, $encoding);
12901
        }
12902
12903
        return self::str_titleize(
12904
            $str,
12905
            null,
12906
            $encoding,
12907
            false,
12908
            $lang,
12909
            $try_to_keep_the_string_length,
12910
            false
12911
        );
12912
    }
12913
12914
    /**
12915
     * alias for "UTF8::to_ascii()"
12916
     *
12917
     * @param string $str
12918
     * @param string $subst_chr
12919
     * @param bool   $strict
12920
     *
12921
     * @psalm-pure
12922
     *
12923
     * @return string
12924
     *
12925
     * @see        UTF8::to_ascii()
12926
     * @deprecated <p>please use "UTF8::to_ascii()"</p>
12927
     */
12928 7
    public static function toAscii(
12929
        string $str,
12930
        string $subst_chr = '?',
12931
        bool $strict = false
12932
    ): string {
12933 7
        return self::to_ascii($str, $subst_chr, $strict);
12934
    }
12935
12936
    /**
12937
     * alias for "UTF8::to_iso8859()"
12938
     *
12939
     * @param string|string[] $str
12940
     *
12941
     * @psalm-pure
12942
     *
12943
     * @return string|string[]
12944
     *
12945
     * @see        UTF8::to_iso8859()
12946
     * @deprecated <p>please use "UTF8::to_iso8859()"</p>
12947
     */
12948 2
    public static function toIso8859($str)
12949
    {
12950 2
        return self::to_iso8859($str);
12951
    }
12952
12953
    /**
12954
     * alias for "UTF8::to_latin1()"
12955
     *
12956
     * @param string|string[] $str
12957
     *
12958
     * @psalm-pure
12959
     *
12960
     * @return string|string[]
12961
     *
12962
     * @see        UTF8::to_iso8859()
12963
     * @deprecated <p>please use "UTF8::to_iso8859()"</p>
12964
     */
12965 2
    public static function toLatin1($str)
12966
    {
12967 2
        return self::to_iso8859($str);
12968
    }
12969
12970
    /**
12971
     * alias for "UTF8::to_utf8()"
12972
     *
12973
     * @param string|string[] $str
12974
     *
12975
     * @psalm-pure
12976
     *
12977
     * @return string|string[]
12978
     *
12979
     * @see        UTF8::to_utf8()
12980
     * @deprecated <p>please use "UTF8::to_utf8()"</p>
12981
     */
12982 2
    public static function toUTF8($str)
12983
    {
12984 2
        return self::to_utf8($str);
12985
    }
12986
12987
    /**
12988
     * Convert a string into ASCII.
12989
     *
12990
     * EXAMPLE: <code>UTF8::to_ascii('déjà σσς iıii'); // 'deja sss iiii'</code>
12991
     *
12992
     * @param string $str     <p>The input string.</p>
12993
     * @param string $unknown [optional] <p>Character use if character unknown. (default is ?)</p>
12994
     * @param bool   $strict  [optional] <p>Use "transliterator_transliterate()" from PHP-Intl | WARNING: bad
12995
     *                        performance</p>
12996
     *
12997
     * @psalm-pure
12998
     *
12999
     * @return string
13000
     */
13001 37
    public static function to_ascii(
13002
        string $str,
13003
        string $unknown = '?',
13004
        bool $strict = false
13005
    ): string {
13006 37
        return ASCII::to_transliterate($str, $unknown, $strict);
13007
    }
13008
13009
    /**
13010
     * @param bool|int|string $str
13011
     *
13012
     * @phpstan-param bool|int|numeric-string $str
13013
     *
13014
     * @psalm-pure
13015
     *
13016
     * @return bool
13017
     */
13018 19
    public static function to_boolean($str): bool
13019
    {
13020
        // init
13021 19
        $str = (string) $str;
13022
13023 19
        if ($str === '') {
13024 2
            return false;
13025
        }
13026
13027
        // Info: http://php.net/manual/en/filter.filters.validate.php
13028
        $map = [
13029 17
            'true'  => true,
13030
            '1'     => true,
13031
            'on'    => true,
13032
            'yes'   => true,
13033
            'false' => false,
13034
            '0'     => false,
13035
            'off'   => false,
13036
            'no'    => false,
13037
        ];
13038
13039 17
        if (isset($map[$str])) {
13040 11
            return $map[$str];
13041
        }
13042
13043 6
        $key = \strtolower($str);
13044 6
        if (isset($map[$key])) {
13045 2
            return $map[$key];
13046
        }
13047
13048 4
        if (\is_numeric($str)) {
13049 2
            return ((float) $str + 0) > 0;
13050
        }
13051
13052 2
        return (bool) \trim($str);
13053
    }
13054
13055
    /**
13056
     * Convert given string to safe filename (and keep string case).
13057
     *
13058
     * @param string $str
13059
     * @param bool   $use_transliterate No transliteration, conversion etc. is done by default - unsafe characters are
13060
     *                                  simply replaced with hyphen.
13061
     * @param string $fallback_char
13062
     *
13063
     * @psalm-pure
13064
     *
13065
     * @return string
13066
     */
13067 1
    public static function to_filename(
13068
        string $str,
13069
        bool $use_transliterate = false,
13070
        string $fallback_char = '-'
13071
    ): string {
13072 1
        return ASCII::to_filename(
13073 1
            $str,
13074 1
            $use_transliterate,
13075 1
            $fallback_char
13076
        );
13077
    }
13078
13079
    /**
13080
     * Convert a string into "ISO-8859"-encoding (Latin-1).
13081
     *
13082
     * EXAMPLE: <code>UTF8::to_utf8(UTF8::to_iso8859('  -ABC-中文空白-  ')); // '  -ABC-????-  '</code>
13083
     *
13084
     * @param string|string[] $str
13085
     *
13086
     * @psalm-pure
13087
     *
13088
     * @return string|string[]
13089
     */
13090 8
    public static function to_iso8859($str)
13091
    {
13092 8
        if (\is_array($str)) {
13093 2
            foreach ($str as $k => &$v) {
13094 2
                $v = self::to_iso8859($v);
13095
            }
13096
13097 2
            return $str;
13098
        }
13099
13100 8
        $str = (string) $str;
13101 8
        if ($str === '') {
13102 2
            return '';
13103
        }
13104
13105 8
        return self::utf8_decode($str);
13106
    }
13107
13108
    /**
13109
     * alias for "UTF8::to_iso8859()"
13110
     *
13111
     * @param string|string[] $str
13112
     *
13113
     * @psalm-pure
13114
     *
13115
     * @return string|string[]
13116
     *
13117
     * @see        UTF8::to_iso8859()
13118
     * @deprecated <p>please use "UTF8::to_iso8859()"</p>
13119
     */
13120 2
    public static function to_latin1($str)
13121
    {
13122 2
        return self::to_iso8859($str);
13123
    }
13124
13125
    /**
13126
     * This function leaves UTF-8 characters alone, while converting almost all non-UTF8 to UTF8.
13127
     *
13128
     * <ul>
13129
     * <li>It decode UTF-8 codepoints and Unicode escape sequences.</li>
13130
     * <li>It assumes that the encoding of the original string is either WINDOWS-1252 or ISO-8859.</li>
13131
     * <li>WARNING: It does not remove invalid UTF-8 characters, so you maybe need to use "UTF8::clean()" for this
13132
     * case.</li>
13133
     * </ul>
13134
     *
13135
     * EXAMPLE: <code>UTF8::to_utf8(["\u0063\u0061\u0074"]); // array('cat')</code>
13136
     *
13137
     * @param string|string[] $str                        <p>Any string or array of strings.</p>
13138
     * @param bool            $decode_html_entity_to_utf8 <p>Set to true, if you need to decode html-entities.</p>
13139
     *
13140
     * @psalm-pure
13141
     *
13142
     * @return string|string[]
13143
     *                         <p>The UTF-8 encoded string</p>
13144
     *
13145
     * @template TToUtf8
13146
     * @phpstan-param TToUtf8 $str
13147
     * @phpstan-return TToUtf8
13148
     *
13149
     * @noinspection SuspiciousBinaryOperationInspection
13150
     */
13151 44
    public static function to_utf8($str, bool $decode_html_entity_to_utf8 = false)
13152
    {
13153 44
        if (\is_array($str)) {
13154 4
            foreach ($str as $k => &$v) {
13155 4
                $v = self::to_utf8_string($v, $decode_html_entity_to_utf8);
13156
            }
13157
13158 4
            return $str;
13159
        }
13160
13161
        /** @phpstan-var TToUtf8 $str */
13162 44
        $str = self::to_utf8_string($str, $decode_html_entity_to_utf8);
13163
13164 44
        return $str;
13165
    }
13166
13167
    /**
13168
     * This function leaves UTF-8 characters alone, while converting almost all non-UTF8 to UTF8.
13169
     *
13170
     * <ul>
13171
     * <li>It decode UTF-8 codepoints and Unicode escape sequences.</li>
13172
     * <li>It assumes that the encoding of the original string is either WINDOWS-1252 or ISO-8859.</li>
13173
     * <li>WARNING: It does not remove invalid UTF-8 characters, so you maybe need to use "UTF8::clean()" for this
13174
     * case.</li>
13175
     * </ul>
13176
     *
13177
     * EXAMPLE: <code>UTF8::to_utf8_string("\u0063\u0061\u0074"); // 'cat'</code>
13178
     *
13179
     * @param string $str                        <p>Any string.</p>
13180
     * @param bool   $decode_html_entity_to_utf8 <p>Set to true, if you need to decode html-entities.</p>
13181
     *
13182
     * @psalm-pure
13183
     *
13184
     * @return string
13185
     *                <p>The UTF-8 encoded string</p>
13186
     *
13187
     * @noinspection SuspiciousBinaryOperationInspection
13188
     */
13189 44
    public static function to_utf8_string(string $str, bool $decode_html_entity_to_utf8 = false): string
13190
    {
13191 44
        if ($str === '') {
13192 7
            return $str;
13193
        }
13194
13195 44
        $max = \strlen($str);
13196 44
        $buf = '';
13197
13198 44
        for ($i = 0; $i < $max; ++$i) {
13199 44
            $c1 = $str[$i];
13200
13201 44
            if ($c1 >= "\xC0") { // should be converted to UTF8, if it's not UTF8 already
13202
13203 40
                if ($c1 <= "\xDF") { // looks like 2 bytes UTF8
13204
13205 36
                    $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
13206
13207 36
                    if ($c2 >= "\x80" && $c2 <= "\xBF") { // yeah, almost sure it's UTF8 already
13208 22
                        $buf .= $c1 . $c2;
13209 22
                        ++$i;
13210
                    } else { // not valid UTF8 - convert it
13211 36
                        $buf .= self::to_utf8_convert_helper($c1);
13212
                    }
13213 37
                } elseif ($c1 >= "\xE0" && $c1 <= "\xEF") { // looks like 3 bytes UTF8
13214
13215 36
                    $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
13216 36
                    $c3 = $i + 2 >= $max ? "\x00" : $str[$i + 2];
13217
13218 36
                    if ($c2 >= "\x80" && $c2 <= "\xBF" && $c3 >= "\x80" && $c3 <= "\xBF") { // yeah, almost sure it's UTF8 already
13219 17
                        $buf .= $c1 . $c2 . $c3;
13220 17
                        $i += 2;
13221
                    } else { // not valid UTF8 - convert it
13222 36
                        $buf .= self::to_utf8_convert_helper($c1);
13223
                    }
13224 28
                } elseif ($c1 >= "\xF0" && $c1 <= "\xF7") { // looks like 4 bytes UTF8
13225
13226 28
                    $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
13227 28
                    $c3 = $i + 2 >= $max ? "\x00" : $str[$i + 2];
13228 28
                    $c4 = $i + 3 >= $max ? "\x00" : $str[$i + 3];
13229
13230 28
                    if ($c2 >= "\x80" && $c2 <= "\xBF" && $c3 >= "\x80" && $c3 <= "\xBF" && $c4 >= "\x80" && $c4 <= "\xBF") { // yeah, almost sure it's UTF8 already
13231 10
                        $buf .= $c1 . $c2 . $c3 . $c4;
13232 10
                        $i += 3;
13233
                    } else { // not valid UTF8 - convert it
13234 28
                        $buf .= self::to_utf8_convert_helper($c1);
13235
                    }
13236
                } else { // doesn't look like UTF8, but should be converted
13237
13238 40
                    $buf .= self::to_utf8_convert_helper($c1);
13239
                }
13240 41
            } elseif (($c1 & "\xC0") === "\x80") { // needs conversion
13241
13242 4
                $buf .= self::to_utf8_convert_helper($c1);
13243
            } else { // it doesn't need conversion
13244
13245 41
                $buf .= $c1;
13246
            }
13247
        }
13248
13249
        // decode unicode escape sequences + unicode surrogate pairs
13250 44
        $buf = \preg_replace_callback(
13251 44
            '/\\\\u([dD][89abAB][0-9a-fA-F]{2})\\\\u([dD][cdefCDEF][\da-fA-F]{2})|\\\\u([0-9a-fA-F]{4})/',
13252
            /**
13253
             * @param array $matches
13254
             *
13255
             * @psalm-pure
13256
             *
13257
             * @return string
13258
             */
13259
            static function (array $matches): string {
13260 13
                if (isset($matches[3])) {
13261 13
                    $cp = (int) \hexdec($matches[3]);
13262
                } else {
13263
                    // http://unicode.org/faq/utf_bom.html#utf16-4
13264 1
                    $cp = ((int) \hexdec($matches[1]) << 10)
13265 1
                          + (int) \hexdec($matches[2])
13266 1
                          + 0x10000
13267 1
                          - (0xD800 << 10)
13268 1
                          - 0xDC00;
13269
                }
13270
13271
                // https://github.com/php/php-src/blob/php-7.3.2/ext/standard/html.c#L471
13272
                //
13273
                // php_utf32_utf8(unsigned char *buf, unsigned k)
13274
13275 13
                if ($cp < 0x80) {
13276 8
                    return (string) self::chr($cp);
13277
                }
13278
13279 10
                if ($cp < 0xA0) {
13280
                    /** @noinspection UnnecessaryCastingInspection */
13281
                    return (string) self::chr(0xC0 | $cp >> 6) . (string) self::chr(0x80 | $cp & 0x3F);
13282
                }
13283
13284 10
                return self::decimal_to_chr($cp);
13285 44
            },
13286 44
            $buf
13287
        );
13288
13289 44
        if ($buf === null) {
13290
            return '';
13291
        }
13292
13293
        // decode UTF-8 codepoints
13294 44
        if ($decode_html_entity_to_utf8) {
13295 3
            $buf = self::html_entity_decode($buf);
13296
        }
13297
13298 44
        return $buf;
13299
    }
13300
13301
    /**
13302
     * Returns the given string as an integer, or null if the string isn't numeric.
13303
     *
13304
     * @param string $str
13305
     *
13306
     * @psalm-pure
13307
     *
13308
     * @return int|null
13309
     *                  <p>null if the string isn't numeric</p>
13310
     */
13311 1
    public static function to_int(string $str)
13312
    {
13313 1
        if (\is_numeric($str)) {
13314 1
            return (int) $str;
13315
        }
13316
13317 1
        return null;
13318
    }
13319
13320
    /**
13321
     * Returns the given input as string, or null if the input isn't int|float|string
13322
     * and do not implement the "__toString()" method.
13323
     *
13324
     * @param float|int|object|string|null $input
13325
     *
13326
     * @psalm-pure
13327
     *
13328
     * @return string|null
13329
     *                     <p>null if the input isn't int|float|string and has no "__toString()" method</p>
13330
     */
13331 1
    public static function to_string($input)
13332
    {
13333 1
        if ($input === null) {
13334
            return null;
13335
        }
13336
13337
        /** @var string $input_type - hack for psalm */
13338 1
        $input_type = \gettype($input);
13339
13340
        if (
13341 1
            $input_type === 'string'
13342
            ||
13343 1
            $input_type === 'integer'
13344
            ||
13345 1
            $input_type === 'float'
13346
            ||
13347 1
            $input_type === 'double'
13348
        ) {
13349 1
            return (string) $input;
13350
        }
13351
13352 1
        if ($input_type === 'object') {
13353
            /** @noinspection PhpSillyAssignmentInspection */
13354
            /** @var object $input - hack for psalm / phpstan */
13355 1
            $input = $input;
13356
            /** @noinspection NestedPositiveIfStatementsInspection */
13357
            /** @noinspection MissingOrEmptyGroupStatementInspection */
13358 1
            if (\method_exists($input, '__toString')) {
13359 1
                return (string) $input;
13360
            }
13361
        }
13362
13363 1
        return null;
13364
    }
13365
13366
    /**
13367
     * Strip whitespace or other characters from the beginning and end of a UTF-8 string.
13368
     *
13369
     * INFO: This is slower then "trim()"
13370
     *
13371
     * We can only use the original-function, if we use <= 7-Bit in the string / chars
13372
     * but the check for ASCII (7-Bit) cost more time, then we can safe here.
13373
     *
13374
     * EXAMPLE: <code>UTF8::trim('   -ABC-中文空白-  '); // '-ABC-中文空白-'</code>
13375
     *
13376
     * @param string      $str   <p>The string to be trimmed</p>
13377
     * @param string|null $chars [optional] <p>Optional characters to be stripped</p>
13378
     *
13379
     * @psalm-pure
13380
     *
13381
     * @return string
13382
     *                <p>The trimmed string.</p>
13383
     */
13384 57
    public static function trim(string $str = '', string $chars = null): string
13385
    {
13386 57
        if ($str === '') {
13387 9
            return '';
13388
        }
13389
13390 50
        if (self::$SUPPORT['mbstring'] === true) {
13391 50
            if ($chars !== null) {
13392
                /** @noinspection PregQuoteUsageInspection */
13393 28
                $chars = \preg_quote($chars);
13394 28
                $pattern = "^[${chars}]+|[${chars}]+\$";
13395
            } else {
13396 22
                $pattern = '^[\\s]+|[\\s]+$';
13397
            }
13398
13399
            /** @noinspection PhpComposerExtensionStubsInspection */
13400 50
            return (string) \mb_ereg_replace($pattern, '', $str);
13401
        }
13402
13403 8
        if ($chars !== null) {
13404
            $chars = \preg_quote($chars, '/');
13405
            $pattern = "^[${chars}]+|[${chars}]+\$";
13406
        } else {
13407 8
            $pattern = '^[\\s]+|[\\s]+$';
13408
        }
13409
13410 8
        return self::regex_replace($str, $pattern, '');
13411
    }
13412
13413
    /**
13414
     * Makes string's first char uppercase.
13415
     *
13416
     * EXAMPLE: <code>UTF8::ucfirst('ñtërnâtiônàlizætiøn foo'); // 'Ñtërnâtiônàlizætiøn foo'</code>
13417
     *
13418
     * @param string      $str                           <p>The input string.</p>
13419
     * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
13420
     * @param bool        $clean_utf8                    [optional] <p>Remove non UTF-8 chars from the string.</p>
13421
     * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
13422
     *                                                   tr</p>
13423
     * @param bool        $try_to_keep_the_string_length [optional] <p>true === try to keep the string length: e.g. ẞ
13424
     *                                                   -> ß</p>
13425
     *
13426
     * @psalm-pure
13427
     *
13428
     * @return string
13429
     *                <p>The resulting string with with char uppercase.</p>
13430
     */
13431 69
    public static function ucfirst(
13432
        string $str,
13433
        string $encoding = 'UTF-8',
13434
        bool $clean_utf8 = false,
13435
        string $lang = null,
13436
        bool $try_to_keep_the_string_length = false
13437
    ): string {
13438 69
        if ($str === '') {
13439 3
            return '';
13440
        }
13441
13442 68
        if ($clean_utf8) {
13443
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
13444
            // if invalid characters are found in $haystack before $needle
13445 1
            $str = self::clean($str);
13446
        }
13447
13448 68
        $use_mb_functions = $lang === null && !$try_to_keep_the_string_length;
13449
13450 68
        if ($encoding === 'UTF-8') {
13451 22
            $str_part_two = (string) \mb_substr($str, 1);
13452
13453 22
            if ($use_mb_functions) {
13454 22
                $str_part_one = \mb_strtoupper(
13455 22
                    (string) \mb_substr($str, 0, 1)
13456
                );
13457
            } else {
13458
                $str_part_one = self::strtoupper(
13459
                    (string) \mb_substr($str, 0, 1),
13460
                    $encoding,
13461
                    false,
13462
                    $lang,
13463 22
                    $try_to_keep_the_string_length
13464
                );
13465
            }
13466
        } else {
13467 47
            $encoding = self::normalize_encoding($encoding, 'UTF-8');
13468
13469 47
            $str_part_two = (string) self::substr($str, 1, null, $encoding);
13470
13471 47
            if ($use_mb_functions) {
13472 47
                $str_part_one = \mb_strtoupper(
13473 47
                    (string) \mb_substr($str, 0, 1, $encoding),
13474 47
                    $encoding
13475
                );
13476
            } else {
13477
                $str_part_one = self::strtoupper(
13478
                    (string) self::substr($str, 0, 1, $encoding),
13479
                    $encoding,
13480
                    false,
13481
                    $lang,
13482
                    $try_to_keep_the_string_length
13483
                );
13484
            }
13485
        }
13486
13487 68
        return $str_part_one . $str_part_two;
13488
    }
13489
13490
    /**
13491
     * alias for "UTF8::ucfirst()"
13492
     *
13493
     * @param string $str
13494
     * @param string $encoding
13495
     * @param bool   $clean_utf8
13496
     *
13497
     * @psalm-pure
13498
     *
13499
     * @return string
13500
     *
13501
     * @see        UTF8::ucfirst()
13502
     * @deprecated <p>please use "UTF8::ucfirst()"</p>
13503
     */
13504 1
    public static function ucword(
13505
        string $str,
13506
        string $encoding = 'UTF-8',
13507
        bool $clean_utf8 = false
13508
    ): string {
13509 1
        return self::ucfirst($str, $encoding, $clean_utf8);
13510
    }
13511
13512
    /**
13513
     * Uppercase for all words in the string.
13514
     *
13515
     * EXAMPLE: <code>UTF8::ucwords('iñt ërn âTi ônà liz æti øn'); // 'Iñt Ërn ÂTi Ônà Liz Æti Øn'</code>
13516
     *
13517
     * @param string   $str        <p>The input string.</p>
13518
     * @param string[] $exceptions [optional] <p>Exclusion for some words.</p>
13519
     * @param string   $char_list  [optional] <p>Additional chars that contains to words and do not start a new
13520
     *                             word.</p>
13521
     * @param string   $encoding   [optional] <p>Set the charset.</p>
13522
     * @param bool     $clean_utf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
13523
     *
13524
     * @psalm-pure
13525
     *
13526
     * @return string
13527
     */
13528 8
    public static function ucwords(
13529
        string $str,
13530
        array $exceptions = [],
13531
        string $char_list = '',
13532
        string $encoding = 'UTF-8',
13533
        bool $clean_utf8 = false
13534
    ): string {
13535 8
        if (!$str) {
13536 2
            return '';
13537
        }
13538
13539
        // INFO: mb_convert_case($str, MB_CASE_TITLE);
13540
        // -> MB_CASE_TITLE didn't only uppercase the first letter, it also lowercase all other letters
13541
13542 7
        if ($clean_utf8) {
13543
            // "mb_strpos()" and "iconv_strpos()" returns wrong position,
13544
            // if invalid characters are found in $haystack before $needle
13545 1
            $str = self::clean($str);
13546
        }
13547
13548 7
        $use_php_default_functions = !(bool) ($char_list . \implode('', $exceptions));
13549
13550
        if (
13551 7
            $use_php_default_functions
13552
            &&
13553 7
            ASCII::is_ascii($str)
13554
        ) {
13555
            return \ucwords($str);
13556
        }
13557
13558 7
        $words = self::str_to_words($str, $char_list);
13559 7
        $use_exceptions = $exceptions !== [];
13560
13561 7
        $words_str = '';
13562 7
        foreach ($words as &$word) {
13563 7
            if (!$word) {
13564 7
                continue;
13565
            }
13566
13567
            if (
13568 7
                !$use_exceptions
13569
                ||
13570 7
                !\in_array($word, $exceptions, true)
13571
            ) {
13572 7
                $words_str .= self::ucfirst($word, $encoding);
13573
            } else {
13574 7
                $words_str .= $word;
13575
            }
13576
        }
13577
13578 7
        return $words_str;
13579
    }
13580
13581
    /**
13582
     * Multi decode HTML entity + fix urlencoded-win1252-chars.
13583
     *
13584
     * EXAMPLE: <code>UTF8::urldecode('tes%20öäü%20\u00edtest+test'); // 'tes öäü ítest test'</code>
13585
     *
13586
     * e.g:
13587
     * 'test+test'                     => 'test test'
13588
     * 'D&#252;sseldorf'               => 'Düsseldorf'
13589
     * 'D%FCsseldorf'                  => 'Düsseldorf'
13590
     * 'D&#xFC;sseldorf'               => 'Düsseldorf'
13591
     * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
13592
     * 'Düsseldorf'                   => 'Düsseldorf'
13593
     * 'D%C3%BCsseldorf'               => 'Düsseldorf'
13594
     * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
13595
     * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
13596
     *
13597
     * @param string $str          <p>The input string.</p>
13598
     * @param bool   $multi_decode <p>Decode as often as possible.</p>
13599
     *
13600
     * @psalm-pure
13601
     *
13602
     * @return string
13603
     */
13604 4
    public static function urldecode(string $str, bool $multi_decode = true): string
13605
    {
13606 4
        if ($str === '') {
13607 3
            return '';
13608
        }
13609
13610
        if (
13611 4
            \strpos($str, '&') === false
13612
            &&
13613 4
            \strpos($str, '%') === false
13614
            &&
13615 4
            \strpos($str, '+') === false
13616
            &&
13617 4
            \strpos($str, '\u') === false
13618
        ) {
13619 3
            return self::fix_simple_utf8($str);
13620
        }
13621
13622 4
        $str = self::urldecode_unicode_helper($str);
13623
13624 4
        if ($multi_decode) {
13625
            do {
13626 3
                $str_compare = $str;
13627
13628
                /**
13629
                 * @psalm-suppress PossiblyInvalidArgument
13630
                 */
13631 3
                $str = self::fix_simple_utf8(
13632 3
                    \urldecode(
13633 3
                        self::html_entity_decode(
13634 3
                            self::to_utf8($str),
13635 3
                            \ENT_QUOTES | \ENT_HTML5
13636
                        )
13637
                    )
13638
                );
13639 3
            } while ($str_compare !== $str);
13640
        } else {
13641
            /**
13642
             * @psalm-suppress PossiblyInvalidArgument
13643
             */
13644 1
            $str = self::fix_simple_utf8(
13645 1
                \urldecode(
13646 1
                    self::html_entity_decode(
13647 1
                        self::to_utf8($str),
13648 1
                        \ENT_QUOTES | \ENT_HTML5
13649
                    )
13650
                )
13651
            );
13652
        }
13653
13654 4
        return $str;
13655
    }
13656
13657
    /**
13658
     * Return a array with "urlencoded"-win1252 -> UTF-8
13659
     *
13660
     * @psalm-pure
13661
     *
13662
     * @return string[]
13663
     *
13664
     * @deprecated <p>please use the "UTF8::urldecode()" function to decode a string</p>
13665
     */
13666 2
    public static function urldecode_fix_win1252_chars(): array
13667
    {
13668
        return [
13669 2
            '%20' => ' ',
13670
            '%21' => '!',
13671
            '%22' => '"',
13672
            '%23' => '#',
13673
            '%24' => '$',
13674
            '%25' => '%',
13675
            '%26' => '&',
13676
            '%27' => "'",
13677
            '%28' => '(',
13678
            '%29' => ')',
13679
            '%2A' => '*',
13680
            '%2B' => '+',
13681
            '%2C' => ',',
13682
            '%2D' => '-',
13683
            '%2E' => '.',
13684
            '%2F' => '/',
13685
            '%30' => '0',
13686
            '%31' => '1',
13687
            '%32' => '2',
13688
            '%33' => '3',
13689
            '%34' => '4',
13690
            '%35' => '5',
13691
            '%36' => '6',
13692
            '%37' => '7',
13693
            '%38' => '8',
13694
            '%39' => '9',
13695
            '%3A' => ':',
13696
            '%3B' => ';',
13697
            '%3C' => '<',
13698
            '%3D' => '=',
13699
            '%3E' => '>',
13700
            '%3F' => '?',
13701
            '%40' => '@',
13702
            '%41' => 'A',
13703
            '%42' => 'B',
13704
            '%43' => 'C',
13705
            '%44' => 'D',
13706
            '%45' => 'E',
13707
            '%46' => 'F',
13708
            '%47' => 'G',
13709
            '%48' => 'H',
13710
            '%49' => 'I',
13711
            '%4A' => 'J',
13712
            '%4B' => 'K',
13713
            '%4C' => 'L',
13714
            '%4D' => 'M',
13715
            '%4E' => 'N',
13716
            '%4F' => 'O',
13717
            '%50' => 'P',
13718
            '%51' => 'Q',
13719
            '%52' => 'R',
13720
            '%53' => 'S',
13721
            '%54' => 'T',
13722
            '%55' => 'U',
13723
            '%56' => 'V',
13724
            '%57' => 'W',
13725
            '%58' => 'X',
13726
            '%59' => 'Y',
13727
            '%5A' => 'Z',
13728
            '%5B' => '[',
13729
            '%5C' => '\\',
13730
            '%5D' => ']',
13731
            '%5E' => '^',
13732
            '%5F' => '_',
13733
            '%60' => '`',
13734
            '%61' => 'a',
13735
            '%62' => 'b',
13736
            '%63' => 'c',
13737
            '%64' => 'd',
13738
            '%65' => 'e',
13739
            '%66' => 'f',
13740
            '%67' => 'g',
13741
            '%68' => 'h',
13742
            '%69' => 'i',
13743
            '%6A' => 'j',
13744
            '%6B' => 'k',
13745
            '%6C' => 'l',
13746
            '%6D' => 'm',
13747
            '%6E' => 'n',
13748
            '%6F' => 'o',
13749
            '%70' => 'p',
13750
            '%71' => 'q',
13751
            '%72' => 'r',
13752
            '%73' => 's',
13753
            '%74' => 't',
13754
            '%75' => 'u',
13755
            '%76' => 'v',
13756
            '%77' => 'w',
13757
            '%78' => 'x',
13758
            '%79' => 'y',
13759
            '%7A' => 'z',
13760
            '%7B' => '{',
13761
            '%7C' => '|',
13762
            '%7D' => '}',
13763
            '%7E' => '~',
13764
            '%7F' => '',
13765
            '%80' => '`',
13766
            '%81' => '',
13767
            '%82' => '‚',
13768
            '%83' => 'ƒ',
13769
            '%84' => '„',
13770
            '%85' => '…',
13771
            '%86' => '†',
13772
            '%87' => '‡',
13773
            '%88' => 'ˆ',
13774
            '%89' => '‰',
13775
            '%8A' => 'Š',
13776
            '%8B' => '‹',
13777
            '%8C' => 'Œ',
13778
            '%8D' => '',
13779
            '%8E' => 'Ž',
13780
            '%8F' => '',
13781
            '%90' => '',
13782
            '%91' => '‘',
13783
            '%92' => '’',
13784
            '%93' => '“',
13785
            '%94' => '”',
13786
            '%95' => '•',
13787
            '%96' => '–',
13788
            '%97' => '—',
13789
            '%98' => '˜',
13790
            '%99' => '™',
13791
            '%9A' => 'š',
13792
            '%9B' => '›',
13793
            '%9C' => 'œ',
13794
            '%9D' => '',
13795
            '%9E' => 'ž',
13796
            '%9F' => 'Ÿ',
13797
            '%A0' => '',
13798
            '%A1' => '¡',
13799
            '%A2' => '¢',
13800
            '%A3' => '£',
13801
            '%A4' => '¤',
13802
            '%A5' => '¥',
13803
            '%A6' => '¦',
13804
            '%A7' => '§',
13805
            '%A8' => '¨',
13806
            '%A9' => '©',
13807
            '%AA' => 'ª',
13808
            '%AB' => '«',
13809
            '%AC' => '¬',
13810
            '%AD' => '',
13811
            '%AE' => '®',
13812
            '%AF' => '¯',
13813
            '%B0' => '°',
13814
            '%B1' => '±',
13815
            '%B2' => '²',
13816
            '%B3' => '³',
13817
            '%B4' => '´',
13818
            '%B5' => 'µ',
13819
            '%B6' => '¶',
13820
            '%B7' => '·',
13821
            '%B8' => '¸',
13822
            '%B9' => '¹',
13823
            '%BA' => 'º',
13824
            '%BB' => '»',
13825
            '%BC' => '¼',
13826
            '%BD' => '½',
13827
            '%BE' => '¾',
13828
            '%BF' => '¿',
13829
            '%C0' => 'À',
13830
            '%C1' => 'Á',
13831
            '%C2' => 'Â',
13832
            '%C3' => 'Ã',
13833
            '%C4' => 'Ä',
13834
            '%C5' => 'Å',
13835
            '%C6' => 'Æ',
13836
            '%C7' => 'Ç',
13837
            '%C8' => 'È',
13838
            '%C9' => 'É',
13839
            '%CA' => 'Ê',
13840
            '%CB' => 'Ë',
13841
            '%CC' => 'Ì',
13842
            '%CD' => 'Í',
13843
            '%CE' => 'Î',
13844
            '%CF' => 'Ï',
13845
            '%D0' => 'Ð',
13846
            '%D1' => 'Ñ',
13847
            '%D2' => 'Ò',
13848
            '%D3' => 'Ó',
13849
            '%D4' => 'Ô',
13850
            '%D5' => 'Õ',
13851
            '%D6' => 'Ö',
13852
            '%D7' => '×',
13853
            '%D8' => 'Ø',
13854
            '%D9' => 'Ù',
13855
            '%DA' => 'Ú',
13856
            '%DB' => 'Û',
13857
            '%DC' => 'Ü',
13858
            '%DD' => 'Ý',
13859
            '%DE' => 'Þ',
13860
            '%DF' => 'ß',
13861
            '%E0' => 'à',
13862
            '%E1' => 'á',
13863
            '%E2' => 'â',
13864
            '%E3' => 'ã',
13865
            '%E4' => 'ä',
13866
            '%E5' => 'å',
13867
            '%E6' => 'æ',
13868
            '%E7' => 'ç',
13869
            '%E8' => 'è',
13870
            '%E9' => 'é',
13871
            '%EA' => 'ê',
13872
            '%EB' => 'ë',
13873
            '%EC' => 'ì',
13874
            '%ED' => 'í',
13875
            '%EE' => 'î',
13876
            '%EF' => 'ï',
13877
            '%F0' => 'ð',
13878
            '%F1' => 'ñ',
13879
            '%F2' => 'ò',
13880
            '%F3' => 'ó',
13881
            '%F4' => 'ô',
13882
            '%F5' => 'õ',
13883
            '%F6' => 'ö',
13884
            '%F7' => '÷',
13885
            '%F8' => 'ø',
13886
            '%F9' => 'ù',
13887
            '%FA' => 'ú',
13888
            '%FB' => 'û',
13889
            '%FC' => 'ü',
13890
            '%FD' => 'ý',
13891
            '%FE' => 'þ',
13892
            '%FF' => 'ÿ',
13893
        ];
13894
    }
13895
13896
    /**
13897
     * Decodes a UTF-8 string to ISO-8859-1.
13898
     *
13899
     * EXAMPLE: <code>UTF8::encode('UTF-8', UTF8::utf8_decode('-ABC-中文空白-')); // '-ABC-????-'</code>
13900
     *
13901
     * @param string $str             <p>The input string.</p>
13902
     * @param bool   $keep_utf8_chars
13903
     *
13904
     * @psalm-pure
13905
     *
13906
     * @return string
13907
     *
13908
     * @noinspection SuspiciousBinaryOperationInspection
13909
     */
13910 14
    public static function utf8_decode(string $str, bool $keep_utf8_chars = false): string
13911
    {
13912 14
        if ($str === '') {
13913 6
            return '';
13914
        }
13915
13916
        // save for later comparision
13917 14
        $str_backup = $str;
13918 14
        $len = \strlen($str);
13919
13920 14
        if (self::$ORD === null) {
13921
            self::$ORD = self::getData('ord');
13922
        }
13923
13924 14
        if (self::$CHR === null) {
13925
            self::$CHR = self::getData('chr');
13926
        }
13927
13928 14
        $no_char_found = '?';
13929
        /** @noinspection ForeachInvariantsInspection */
13930 14
        for ($i = 0, $j = 0; $i < $len; ++$i, ++$j) {
13931 14
            switch ($str[$i] & "\xF0") {
13932 14
                case "\xC0":
13933 13
                case "\xD0":
13934 13
                    $c = (self::$ORD[$str[$i] & "\x1F"] << 6) | self::$ORD[$str[++$i] & "\x3F"];
13935 13
                    $str[$j] = $c < 256 ? self::$CHR[$c] : $no_char_found;
13936
13937 13
                    break;
13938
13939
                /** @noinspection PhpMissingBreakStatementInspection */
13940 13
                case "\xF0":
13941
                    ++$i;
13942
13943
                // no break
13944
13945 13
                case "\xE0":
13946 11
                    $str[$j] = $no_char_found;
13947 11
                    $i += 2;
13948
13949 11
                    break;
13950
13951
                default:
13952 12
                    $str[$j] = $str[$i];
13953
            }
13954
        }
13955
13956
        /** @var false|string $return - needed for PhpStan (stubs error) */
13957 14
        $return = \substr($str, 0, $j);
13958 14
        if ($return === false) {
13959
            $return = '';
13960
        }
13961
13962
        if (
13963 14
            $keep_utf8_chars
13964
            &&
13965 14
            (int) self::strlen($return) >= (int) self::strlen($str_backup)
13966
        ) {
13967 2
            return $str_backup;
13968
        }
13969
13970 14
        return $return;
13971
    }
13972
13973
    /**
13974
     * Encodes an ISO-8859-1 string to UTF-8.
13975
     *
13976
     * EXAMPLE: <code>UTF8::utf8_decode(UTF8::utf8_encode('-ABC-中文空白-')); // '-ABC-中文空白-'</code>
13977
     *
13978
     * @param string $str <p>The input string.</p>
13979
     *
13980
     * @psalm-pure
13981
     *
13982
     * @return string
13983
     */
13984 16
    public static function utf8_encode(string $str): string
13985
    {
13986 16
        if ($str === '') {
13987 14
            return '';
13988
        }
13989
13990
        /** @var false|string $str - the polyfill maybe return false */
13991 16
        $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

13991
        $str = \utf8_encode(/** @scrutinizer ignore-type */ $str);
Loading history...
13992
13993
        /** @noinspection CallableParameterUseCaseInTypeContextInspection */
13994
        /** @psalm-suppress TypeDoesNotContainType */
13995 16
        if ($str === false) {
13996
            return '';
13997
        }
13998
13999 16
        return $str;
14000
    }
14001
14002
    /**
14003
     * fix -> utf8-win1252 chars
14004
     *
14005
     * @param string $str <p>The input string.</p>
14006
     *
14007
     * @psalm-pure
14008
     *
14009
     * @return string
14010
     *
14011
     * @deprecated <p>please use "UTF8::fix_simple_utf8()"</p>
14012
     */
14013 2
    public static function utf8_fix_win1252_chars(string $str): string
14014
    {
14015 2
        return self::fix_simple_utf8($str);
14016
    }
14017
14018
    /**
14019
     * Returns an array with all utf8 whitespace characters.
14020
     *
14021
     * @see http://www.bogofilter.org/pipermail/bogofilter/2003-March/001889.html
14022
     *
14023
     * @psalm-pure
14024
     *
14025
     * @return string[]
14026
     *                  An array with all known whitespace characters as values and the type of whitespace as keys
14027
     *                  as defined in above URL
14028
     */
14029 2
    public static function whitespace_table(): array
14030
    {
14031 2
        return self::$WHITESPACE_TABLE;
14032
    }
14033
14034
    /**
14035
     * Limit the number of words in a string.
14036
     *
14037
     * EXAMPLE: <code>UTF8::words_limit('fòô bàř fòô', 2, ''); // 'fòô bàř'</code>
14038
     *
14039
     * @param string $str        <p>The input string.</p>
14040
     * @param int    $limit      <p>The limit of words as integer.</p>
14041
     * @param string $str_add_on <p>Replacement for the striped string.</p>
14042
     *
14043
     * @psalm-pure
14044
     *
14045
     * @return string
14046
     */
14047 2
    public static function words_limit(
14048
        string $str,
14049
        int $limit = 100,
14050
        string $str_add_on = '…'
14051
    ): string {
14052 2
        if ($str === '' || $limit < 1) {
14053 2
            return '';
14054
        }
14055
14056 2
        \preg_match('/^\\s*+(?:[^\\s]++\\s*+){1,' . $limit . '}/u', $str, $matches);
14057
14058
        if (
14059 2
            !isset($matches[0])
14060
            ||
14061 2
            \mb_strlen($str) === (int) \mb_strlen($matches[0])
14062
        ) {
14063 2
            return $str;
14064
        }
14065
14066 2
        return \rtrim($matches[0]) . $str_add_on;
14067
    }
14068
14069
    /**
14070
     * Wraps a string to a given number of characters
14071
     *
14072
     * EXAMPLE: <code>UTF8::wordwrap('Iñtërnâtiônàlizætiøn', 2, '<br>', true)); // 'Iñ<br>të<br>rn<br>ât<br>iô<br>nà<br>li<br>zæ<br>ti<br>øn'</code>
14073
     *
14074
     * @see http://php.net/manual/en/function.wordwrap.php
14075
     *
14076
     * @param string $str   <p>The input string.</p>
14077
     * @param int    $width [optional] <p>The column width.</p>
14078
     * @param string $break [optional] <p>The line is broken using the optional break parameter.</p>
14079
     * @param bool   $cut   [optional] <p>
14080
     *                      If the cut is set to true, the string is
14081
     *                      always wrapped at or before the specified width. So if you have
14082
     *                      a word that is larger than the given width, it is broken apart.
14083
     *                      </p>
14084
     *
14085
     * @psalm-pure
14086
     *
14087
     * @return string
14088
     *                <p>The given string wrapped at the specified column.</p>
14089
     */
14090 12
    public static function wordwrap(
14091
        string $str,
14092
        int $width = 75,
14093
        string $break = "\n",
14094
        bool $cut = false
14095
    ): string {
14096 12
        if ($str === '' || $break === '') {
14097 4
            return '';
14098
        }
14099
14100 10
        $str_split = \explode($break, $str);
14101 10
        if ($str_split === false) {
14102
            return '';
14103
        }
14104
14105
        /** @var string[] $charsArray */
14106 10
        $charsArray = [];
14107 10
        $word_split = '';
14108 10
        foreach ($str_split as $i => $i_value) {
14109 10
            if ($i) {
14110 3
                $charsArray[] = $break;
14111 3
                $word_split .= '#';
14112
            }
14113
14114 10
            foreach (self::str_split($i_value) as $c) {
14115 10
                $charsArray[] = $c;
14116 10
                if ($c === ' ') {
14117 3
                    $word_split .= ' ';
14118
                } else {
14119 10
                    $word_split .= '?';
14120
                }
14121
            }
14122
        }
14123
14124 10
        $str_return = '';
14125 10
        $j = 0;
14126 10
        $b = -1;
14127 10
        $i = -1;
14128 10
        $word_split = \wordwrap($word_split, $width, '#', $cut);
14129
14130 10
        $max = \mb_strlen($word_split);
14131 10
        while (($b = \mb_strpos($word_split, '#', $b + 1)) !== false) {
14132 8
            for (++$i; $i < $b; ++$i) {
14133 8
                if (isset($charsArray[$j])) {
14134 8
                    $str_return .= $charsArray[$j];
14135 8
                    unset($charsArray[$j]);
14136
                }
14137 8
                ++$j;
14138
14139
                // prevent endless loop, e.g. if there is a error in the "mb_*" polyfill
14140 8
                if ($i > $max) {
14141
                    break 2;
14142
                }
14143
            }
14144
14145
            if (
14146 8
                $break === $charsArray[$j]
14147
                ||
14148 8
                $charsArray[$j] === ' '
14149
            ) {
14150 5
                unset($charsArray[$j++]);
14151
            }
14152
14153 8
            $str_return .= $break;
14154
14155
            // prevent endless loop, e.g. if there is a error in the "mb_*" polyfill
14156 8
            if ($b > $max) {
14157
                break;
14158
            }
14159
        }
14160
14161 10
        return $str_return . \implode('', $charsArray);
14162
    }
14163
14164
    /**
14165
     * Line-Wrap the string after $limit, but split the string by "$delimiter" before ...
14166
     *    ... so that we wrap the per line.
14167
     *
14168
     * @param string      $str             <p>The input string.</p>
14169
     * @param int         $width           [optional] <p>The column width.</p>
14170
     * @param string      $break           [optional] <p>The line is broken using the optional break parameter.</p>
14171
     * @param bool        $cut             [optional] <p>
14172
     *                                     If the cut is set to true, the string is
14173
     *                                     always wrapped at or before the specified width. So if you have
14174
     *                                     a word that is larger than the given width, it is broken apart.
14175
     *                                     </p>
14176
     * @param bool        $add_final_break [optional] <p>
14177
     *                                     If this flag is true, then the method will add a $break at the end
14178
     *                                     of the result string.
14179
     *                                     </p>
14180
     * @param string|null $delimiter       [optional] <p>
14181
     *                                     You can change the default behavior, where we split the string by newline.
14182
     *                                     </p>
14183
     *
14184
     * @psalm-pure
14185
     *
14186
     * @return string
14187
     */
14188 1
    public static function wordwrap_per_line(
14189
        string $str,
14190
        int $width = 75,
14191
        string $break = "\n",
14192
        bool $cut = false,
14193
        bool $add_final_break = true,
14194
        string $delimiter = null
14195
    ): string {
14196 1
        if ($delimiter === null) {
14197 1
            $strings = \preg_split('/\\r\\n|\\r|\\n/', $str);
14198
        } else {
14199 1
            $strings = \explode($delimiter, $str);
14200
        }
14201
14202 1
        $string_helper_array = [];
14203 1
        if ($strings !== false) {
14204 1
            foreach ($strings as $value) {
14205 1
                $string_helper_array[] = self::wordwrap($value, $width, $break, $cut);
14206
            }
14207
        }
14208
14209 1
        if ($add_final_break) {
14210 1
            $final_break = $break;
14211
        } else {
14212 1
            $final_break = '';
14213
        }
14214
14215 1
        return \implode($delimiter ?? "\n", $string_helper_array) . $final_break;
14216
    }
14217
14218
    /**
14219
     * Returns an array of Unicode White Space characters.
14220
     *
14221
     * @psalm-pure
14222
     *
14223
     * @return string[]
14224
     *                  <p>An array with numeric code point as key and White Space Character as value.</p>
14225
     */
14226 2
    public static function ws(): array
14227
    {
14228 2
        return self::$WHITESPACE;
14229
    }
14230
14231
    /**
14232
     * Checks whether the passed string contains only byte sequences that are valid UTF-8 characters.
14233
     *
14234
     * EXAMPLE: <code>
14235
     * UTF8::is_utf8_string('Iñtërnâtiônàlizætiøn']); // true
14236
     * //
14237
     * UTF8::is_utf8_string("Iñtërnâtiônàlizætiøn\xA0\xA1"); // false
14238
     * </code>
14239
     *
14240
     * @see          http://hsivonen.iki.fi/php-utf8/
14241
     *
14242
     * @param string $str    <p>The string to be checked.</p>
14243
     * @param bool   $strict <p>Check also if the string is not UTF-16 or UTF-32.</p>
14244
     *
14245
     * @psalm-pure
14246
     *
14247
     * @return bool
14248
     *
14249
     * @noinspection ReturnTypeCanBeDeclaredInspection
14250
     */
14251 110
    private static function is_utf8_string(string $str, bool $strict = false)
14252
    {
14253 110
        if ($str === '') {
14254 15
            return true;
14255
        }
14256
14257 103
        if ($strict) {
14258 2
            $is_binary = self::is_binary($str, true);
14259
14260 2
            if ($is_binary && self::is_utf16($str, false) !== false) {
14261 2
                return false;
14262
            }
14263
14264
            if ($is_binary && self::is_utf32($str, false) !== false) {
14265
                return false;
14266
            }
14267
        }
14268
14269 103
        if (self::$SUPPORT['pcre_utf8']) {
14270
            // If even just the first character can be matched, when the /u
14271
            // modifier is used, then it's valid UTF-8. If the UTF-8 is somehow
14272
            // invalid, nothing at all will match, even if the string contains
14273
            // some valid sequences
14274 103
            return \preg_match('/^./us', $str) === 1;
14275
        }
14276
14277 2
        $mState = 0; // cached expected number of octets after the current octet
14278
        // until the beginning of the next UTF8 character sequence
14279 2
        $mUcs4 = 0; // cached Unicode character
14280 2
        $mBytes = 1; // cached expected number of octets in the current sequence
14281
14282 2
        if (self::$ORD === null) {
14283
            self::$ORD = self::getData('ord');
14284
        }
14285
14286 2
        $len = \strlen($str);
14287
        /** @noinspection ForeachInvariantsInspection */
14288 2
        for ($i = 0; $i < $len; ++$i) {
14289 2
            $in = self::$ORD[$str[$i]];
14290
14291 2
            if ($mState === 0) {
14292
                // When mState is zero we expect either a US-ASCII character or a
14293
                // multi-octet sequence.
14294 2
                if ((0x80 & $in) === 0) {
14295
                    // US-ASCII, pass straight through.
14296 2
                    $mBytes = 1;
14297 2
                } elseif ((0xE0 & $in) === 0xC0) {
14298
                    // First octet of 2 octet sequence.
14299 2
                    $mUcs4 = $in;
14300 2
                    $mUcs4 = ($mUcs4 & 0x1F) << 6;
14301 2
                    $mState = 1;
14302 2
                    $mBytes = 2;
14303 2
                } elseif ((0xF0 & $in) === 0xE0) {
14304
                    // First octet of 3 octet sequence.
14305 2
                    $mUcs4 = $in;
14306 2
                    $mUcs4 = ($mUcs4 & 0x0F) << 12;
14307 2
                    $mState = 2;
14308 2
                    $mBytes = 3;
14309
                } elseif ((0xF8 & $in) === 0xF0) {
14310
                    // First octet of 4 octet sequence.
14311
                    $mUcs4 = $in;
14312
                    $mUcs4 = ($mUcs4 & 0x07) << 18;
14313
                    $mState = 3;
14314
                    $mBytes = 4;
14315
                } elseif ((0xFC & $in) === 0xF8) {
14316
                    /* First octet of 5 octet sequence.
14317
                     *
14318
                     * This is illegal because the encoded codepoint must be either
14319
                     * (a) not the shortest form or
14320
                     * (b) outside the Unicode range of 0-0x10FFFF.
14321
                     * Rather than trying to resynchronize, we will carry on until the end
14322
                     * of the sequence and let the later error handling code catch it.
14323
                     */
14324
                    $mUcs4 = $in;
14325
                    $mUcs4 = ($mUcs4 & 0x03) << 24;
14326
                    $mState = 4;
14327
                    $mBytes = 5;
14328
                } elseif ((0xFE & $in) === 0xFC) {
14329
                    // First octet of 6 octet sequence, see comments for 5 octet sequence.
14330
                    $mUcs4 = $in;
14331
                    $mUcs4 = ($mUcs4 & 1) << 30;
14332
                    $mState = 5;
14333
                    $mBytes = 6;
14334
                } else {
14335
                    // Current octet is neither in the US-ASCII range nor a legal first
14336
                    // octet of a multi-octet sequence.
14337 2
                    return false;
14338
                }
14339 2
            } elseif ((0xC0 & $in) === 0x80) {
14340
14341
                // When mState is non-zero, we expect a continuation of the multi-octet
14342
                // sequence
14343
14344
                // Legal continuation.
14345 2
                $shift = ($mState - 1) * 6;
14346 2
                $tmp = $in;
14347 2
                $tmp = ($tmp & 0x0000003F) << $shift;
14348 2
                $mUcs4 |= $tmp;
14349
                // Prefix: End of the multi-octet sequence. mUcs4 now contains the final
14350
                // Unicode code point to be output.
14351 2
                if (--$mState === 0) {
14352
                    // Check for illegal sequences and code points.
14353
                    //
14354
                    // From Unicode 3.1, non-shortest form is illegal
14355
                    if (
14356 2
                        ($mBytes === 2 && $mUcs4 < 0x0080)
14357
                        ||
14358 2
                        ($mBytes === 3 && $mUcs4 < 0x0800)
14359
                        ||
14360 2
                        ($mBytes === 4 && $mUcs4 < 0x10000)
14361
                        ||
14362 2
                        ($mBytes > 4)
14363
                        ||
14364
                        // From Unicode 3.2, surrogate characters are illegal.
14365 2
                        (($mUcs4 & 0xFFFFF800) === 0xD800)
14366
                        ||
14367
                        // Code points outside the Unicode range are illegal.
14368 2
                        ($mUcs4 > 0x10FFFF)
14369
                    ) {
14370
                        return false;
14371
                    }
14372
                    // initialize UTF8 cache
14373 2
                    $mState = 0;
14374 2
                    $mUcs4 = 0;
14375 2
                    $mBytes = 1;
14376
                }
14377
            } else {
14378
                // ((0xC0 & (*in) != 0x80) && (mState != 0))
14379
                // Incomplete multi-octet sequence.
14380
                return false;
14381
            }
14382
        }
14383
14384 2
        return $mState === 0;
14385
    }
14386
14387
    /**
14388
     * @param string $str
14389
     * @param bool   $use_lowercase      <p>Use uppercase by default, otherwise use lowercase.</p>
14390
     * @param bool   $use_full_case_fold <p>Convert not only common cases.</p>
14391
     *
14392
     * @psalm-pure
14393
     *
14394
     * @return string
14395
     *
14396
     * @noinspection ReturnTypeCanBeDeclaredInspection
14397
     */
14398 33
    private static function fixStrCaseHelper(
14399
        string $str,
14400
        bool $use_lowercase = false,
14401
        bool $use_full_case_fold = false
14402
    ) {
14403 33
        $upper = self::$COMMON_CASE_FOLD['upper'];
14404 33
        $lower = self::$COMMON_CASE_FOLD['lower'];
14405
14406 33
        if ($use_lowercase) {
14407 2
            $str = \str_replace(
14408 2
                $upper,
14409 2
                $lower,
14410 2
                $str
14411
            );
14412
        } else {
14413 31
            $str = \str_replace(
14414 31
                $lower,
14415 31
                $upper,
14416 31
                $str
14417
            );
14418
        }
14419
14420 33
        if ($use_full_case_fold) {
14421
            /**
14422
             * @psalm-suppress ImpureStaticVariable
14423
             *
14424
             * @var array<mixed>|null
14425
             */
14426 31
            static $FULL_CASE_FOLD = null;
14427 31
            if ($FULL_CASE_FOLD === null) {
14428 1
                $FULL_CASE_FOLD = self::getData('caseFolding_full');
14429
            }
14430
14431 31
            if ($use_lowercase) {
14432 2
                $str = \str_replace($FULL_CASE_FOLD[0], $FULL_CASE_FOLD[1], $str);
14433
            } else {
14434 29
                $str = \str_replace($FULL_CASE_FOLD[1], $FULL_CASE_FOLD[0], $str);
14435
            }
14436
        }
14437
14438 33
        return $str;
14439
    }
14440
14441
    /**
14442
     * get data from "/data/*.php"
14443
     *
14444
     * @param string $file
14445
     *
14446
     * @psalm-pure
14447
     *
14448
     * @return array
14449
     *
14450
     * @noinspection ReturnTypeCanBeDeclaredInspection
14451
     */
14452 6
    private static function getData(string $file)
14453
    {
14454
        /** @noinspection PhpIncludeInspection */
14455
        /** @noinspection UsingInclusionReturnValueInspection */
14456
        /** @psalm-suppress UnresolvableInclude */
14457 6
        return include __DIR__ . '/data/' . $file . '.php';
14458
    }
14459
14460
    /**
14461
     * @psalm-pure
14462
     *
14463
     * @return true|null
14464
     */
14465 12
    private static function initEmojiData()
14466
    {
14467 12
        if (self::$EMOJI_KEYS_CACHE === null) {
14468 1
            if (self::$EMOJI === null) {
14469 1
                self::$EMOJI = self::getData('emoji');
14470
            }
14471
14472
            /**
14473
             * @psalm-suppress ImpureFunctionCall - static sort function is used
14474
             */
14475 1
            \uksort(
14476 1
                self::$EMOJI,
14477
                static function (string $a, string $b): int {
14478 1
                    return \strlen($b) <=> \strlen($a);
14479 1
                }
14480
            );
14481
14482 1
            self::$EMOJI_KEYS_CACHE = \array_keys(self::$EMOJI);
14483 1
            self::$EMOJI_VALUES_CACHE = self::$EMOJI;
14484
14485 1
            foreach (self::$EMOJI_KEYS_CACHE as $key) {
14486 1
                $tmp_key = \crc32($key);
14487 1
                self::$EMOJI_KEYS_REVERSIBLE_CACHE[] = '_-_PORTABLE_UTF8_-_' . $tmp_key . '_-_' . \strrev((string) $tmp_key) . '_-_8FTU_ELBATROP_-_';
14488
            }
14489
14490 1
            return true;
14491
        }
14492
14493 12
        return null;
14494
    }
14495
14496
    /**
14497
     * Checks whether mbstring "overloaded" is active on the server.
14498
     *
14499
     * @psalm-pure
14500
     *
14501
     * @return bool
14502
     *
14503
     * @noinspection ReturnTypeCanBeDeclaredInspection
14504
     */
14505
    private static function mbstring_overloaded()
14506
    {
14507
        /**
14508
         * INI directive 'mbstring.func_overload' is deprecated since PHP 7.2
14509
         */
14510
14511
        /** @noinspection PhpComposerExtensionStubsInspection */
14512
        /** @noinspection PhpUsageOfSilenceOperatorInspection */
14513
        return \defined('MB_OVERLOAD_STRING')
14514
               &&
14515
               ((int) @\ini_get('mbstring.func_overload') & \MB_OVERLOAD_STRING);
14516
    }
14517
14518
    /**
14519
     * @param array    $strings
14520
     * @param bool     $remove_empty_values
14521
     * @param int|null $remove_short_values
14522
     *
14523
     * @psalm-pure
14524
     *
14525
     * @return array
14526
     *
14527
     * @noinspection ReturnTypeCanBeDeclaredInspection
14528
     */
14529 2
    private static function reduce_string_array(
14530
        array $strings,
14531
        bool $remove_empty_values,
14532
        int $remove_short_values = null
14533
    ) {
14534
        // init
14535 2
        $return = [];
14536
14537 2
        foreach ($strings as &$str) {
14538
            if (
14539 2
                $remove_short_values !== null
14540
                &&
14541 2
                \mb_strlen($str) <= $remove_short_values
14542
            ) {
14543 2
                continue;
14544
            }
14545
14546
            if (
14547 2
                $remove_empty_values
14548
                &&
14549 2
                \trim($str) === ''
14550
            ) {
14551 2
                continue;
14552
            }
14553
14554 2
            $return[] = $str;
14555
        }
14556
14557 2
        return $return;
14558
    }
14559
14560
    /**
14561
     * rxClass
14562
     *
14563
     * @param string $s
14564
     * @param string $class
14565
     *
14566
     * @psalm-pure
14567
     *
14568
     * @return string
14569
     *
14570
     * @noinspection ReturnTypeCanBeDeclaredInspection
14571
     */
14572 33
    private static function rxClass(string $s, string $class = '')
14573
    {
14574
        /**
14575
         * @psalm-suppress ImpureStaticVariable
14576
         *
14577
         * @var array<string,string>
14578
         */
14579 33
        static $RX_CLASS_CACHE = [];
14580
14581 33
        $cache_key = $s . '_' . $class;
14582
14583 33
        if (isset($RX_CLASS_CACHE[$cache_key])) {
14584 21
            return $RX_CLASS_CACHE[$cache_key];
14585
        }
14586
14587
        /** @var string[] $class_array */
14588 16
        $class_array[] = $class;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$class_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $class_array = array(); before regardless.
Loading history...
14589
14590
        /** @noinspection SuspiciousLoopInspection */
14591
        /** @noinspection AlterInForeachInspection */
14592 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...
14593 15
            if ($s === '-') {
14594
                $class_array[0] = '-' . $class_array[0];
14595 15
            } elseif (!isset($s[2])) {
14596 15
                $class_array[0] .= \preg_quote($s, '/');
14597 1
            } elseif (self::strlen($s) === 1) {
14598 1
                $class_array[0] .= $s;
14599
            } else {
14600 15
                $class_array[] = $s;
14601
            }
14602
        }
14603
14604 16
        if ($class_array[0]) {
14605 16
            $class_array[0] = '[' . $class_array[0] . ']';
14606
        }
14607
14608 16
        if (\count($class_array) === 1) {
14609 16
            $return = $class_array[0];
14610
        } else {
14611
            $return = '(?:' . \implode('|', $class_array) . ')';
14612
        }
14613
14614 16
        $RX_CLASS_CACHE[$cache_key] = $return;
14615
14616 16
        return $return;
14617
    }
14618
14619
    /**
14620
     * Personal names such as "Marcus Aurelius" are sometimes typed incorrectly using lowercase ("marcus aurelius").
14621
     *
14622
     * @param string $names
14623
     * @param string $delimiter
14624
     * @param string $encoding
14625
     *
14626
     * @psalm-pure
14627
     *
14628
     * @return string
14629
     *
14630
     * @noinspection ReturnTypeCanBeDeclaredInspection
14631
     */
14632 1
    private static function str_capitalize_name_helper(
14633
        string $names,
14634
        string $delimiter,
14635
        string $encoding = 'UTF-8'
14636
    ) {
14637
        // init
14638 1
        $name_helper_array = \explode($delimiter, $names);
14639 1
        if ($name_helper_array === false) {
14640
            return '';
14641
        }
14642
14643
        $special_cases = [
14644 1
            'names' => [
14645
                'ab',
14646
                'af',
14647
                'al',
14648
                'and',
14649
                'ap',
14650
                'bint',
14651
                'binte',
14652
                'da',
14653
                'de',
14654
                'del',
14655
                'den',
14656
                'der',
14657
                'di',
14658
                'dit',
14659
                'ibn',
14660
                'la',
14661
                'mac',
14662
                'nic',
14663
                'of',
14664
                'ter',
14665
                'the',
14666
                'und',
14667
                'van',
14668
                'von',
14669
                'y',
14670
                'zu',
14671
            ],
14672
            'prefixes' => [
14673
                'al-',
14674
                "d'",
14675
                'ff',
14676
                "l'",
14677
                'mac',
14678
                'mc',
14679
                'nic',
14680
            ],
14681
        ];
14682
14683 1
        foreach ($name_helper_array as &$name) {
14684 1
            if (\in_array($name, $special_cases['names'], true)) {
14685 1
                continue;
14686
            }
14687
14688 1
            $continue = false;
14689
14690 1
            if ($delimiter === '-') {
14691
                /** @noinspection AlterInForeachInspection */
14692 1
                foreach ((array) $special_cases['names'] as &$beginning) {
14693 1
                    if (\strncmp($name, $beginning, \strlen($beginning)) === 0) {
14694 1
                        $continue = true;
14695
14696 1
                        break;
14697
                    }
14698
                }
14699
            }
14700
14701
            /** @noinspection AlterInForeachInspection */
14702 1
            foreach ((array) $special_cases['prefixes'] as &$beginning) {
14703 1
                if (\strncmp($name, $beginning, \strlen($beginning)) === 0) {
14704 1
                    $continue = true;
14705
14706 1
                    break;
14707
                }
14708
            }
14709
14710 1
            if ($continue) {
14711 1
                continue;
14712
            }
14713
14714 1
            $name = self::ucfirst($name);
14715
        }
14716
14717 1
        return \implode($delimiter, $name_helper_array);
14718
    }
14719
14720
    /**
14721
     * Generic case-sensitive transformation for collation matching.
14722
     *
14723
     * @param string $str <p>The input string</p>
14724
     *
14725
     * @psalm-pure
14726
     *
14727
     * @return string|null
14728
     */
14729 6
    private static function strtonatfold(string $str)
14730
    {
14731 6
        $str = \Normalizer::normalize($str, \Normalizer::NFD);
14732
        /** @phpstan-ignore-next-line - https://github.com/JetBrains/phpstorm-stubs/pull/949 */
14733 6
        if ($str === false) {
14734 2
            return '';
14735
        }
14736
14737
        /** @noinspection PhpUndefinedClassInspection */
14738 6
        return \preg_replace(
14739 6
            '/\p{Mn}+/u',
14740 6
            '',
14741 6
            $str
14742
        );
14743
    }
14744
14745
    /**
14746
     * @param int|string $input
14747
     *
14748
     * @psalm-pure
14749
     *
14750
     * @return string
14751
     *
14752
     * @noinspection ReturnTypeCanBeDeclaredInspection
14753
     * @noinspection SuspiciousBinaryOperationInspection
14754
     */
14755 32
    private static function to_utf8_convert_helper($input)
14756
    {
14757
        // init
14758 32
        $buf = '';
14759
14760 32
        if (self::$ORD === null) {
14761 1
            self::$ORD = self::getData('ord');
14762
        }
14763
14764 32
        if (self::$CHR === null) {
14765 1
            self::$CHR = self::getData('chr');
14766
        }
14767
14768 32
        if (self::$WIN1252_TO_UTF8 === null) {
14769 1
            self::$WIN1252_TO_UTF8 = self::getData('win1252_to_utf8');
14770
        }
14771
14772 32
        $ordC1 = self::$ORD[$input];
14773 32
        if (isset(self::$WIN1252_TO_UTF8[$ordC1])) { // found in Windows-1252 special cases
14774 32
            $buf .= self::$WIN1252_TO_UTF8[$ordC1];
14775
        } else {
14776
            /** @noinspection OffsetOperationsInspection */
14777 1
            $cc1 = self::$CHR[$ordC1 / 64] | "\xC0";
14778 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...
14779 1
            $buf .= $cc1 . $cc2;
14780
        }
14781
14782 32
        return $buf;
14783
    }
14784
14785
    /**
14786
     * @param string $str
14787
     *
14788
     * @psalm-pure
14789
     *
14790
     * @return string
14791
     *
14792
     * @noinspection ReturnTypeCanBeDeclaredInspection
14793
     */
14794 10
    private static function urldecode_unicode_helper(string $str)
14795
    {
14796 10
        $pattern = '/%u([0-9a-fA-F]{3,4})/';
14797 10
        if (\preg_match($pattern, $str)) {
14798 7
            $str = (string) \preg_replace($pattern, '&#x\\1;', $str);
14799
        }
14800
14801 10
        return $str;
14802
    }
14803
}
14804