PluginProbe ʕ •ᴥ•ʔ
FAPI Member / trunk
FAPI Member vtrunk
2.2.33 2.2.32 trunk 1.9.47 2.1.18 2.2.24 2.2.25 2.2.26 2.2.28 2.2.29 2.2.30 2.2.31
fapi-member / libs / nette / utils / src / Utils / Strings.php
fapi-member / libs / nette / utils / src / Utils Last commit date
ArrayHash.php 2 years ago ArrayList.php 2 years ago Arrays.php 2 years ago Callback.php 2 years ago DateTime.php 2 years ago FileSystem.php 2 years ago Floats.php 2 years ago Helpers.php 2 years ago Html.php 2 years ago Image.php 2 years ago Json.php 2 years ago ObjectHelpers.php 2 years ago ObjectMixin.php 2 years ago Paginator.php 2 years ago Random.php 2 years ago Reflection.php 2 years ago Strings.php 2 years ago Type.php 2 years ago Validators.php 2 years ago exceptions.php 2 years ago
Strings.php
458 lines
1 <?php
2
3 /**
4 * This file is part of the Nette Framework (https://nette.org)
5 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6 */
7 declare (strict_types=1);
8 namespace FapiMember\Library\Nette\Utils;
9
10 use FapiMember\Library\JetBrains\PhpStorm\Language;
11 use FapiMember\Library\Nette;
12 use function is_array, is_object, strlen;
13 /**
14 * String tools library.
15 */
16 class Strings
17 {
18 use Nette\StaticClass;
19 public const TRIM_CHARACTERS = " \t\n\r\x00\v ";
20 /**
21 * Checks if the string is valid in UTF-8 encoding.
22 */
23 public static function checkEncoding(string $s): bool
24 {
25 return $s === self::fixEncoding($s);
26 }
27 /**
28 * Removes all invalid UTF-8 characters from a string.
29 */
30 public static function fixEncoding(string $s): string
31 {
32 // removes xD800-xDFFF, x110000 and higher
33 return htmlspecialchars_decode(htmlspecialchars($s, \ENT_NOQUOTES | \ENT_IGNORE, 'UTF-8'), \ENT_NOQUOTES);
34 }
35 /**
36 * Returns a specific character in UTF-8 from code point (number in range 0x0000..D7FF or 0xE000..10FFFF).
37 * @throws Nette\InvalidArgumentException if code point is not in valid range
38 */
39 public static function chr(int $code): string
40 {
41 if ($code < 0 || $code >= 0xd800 && $code <= 0xdfff || $code > 0x10ffff) {
42 throw new Nette\InvalidArgumentException('Code point must be in range 0x0 to 0xD7FF or 0xE000 to 0x10FFFF.');
43 } elseif (!extension_loaded('iconv')) {
44 throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
45 }
46 return iconv('UTF-32BE', 'UTF-8//IGNORE', pack('N', $code));
47 }
48 /**
49 * Starts the $haystack string with the prefix $needle?
50 */
51 public static function startsWith(string $haystack, string $needle): bool
52 {
53 return strncmp($haystack, $needle, strlen($needle)) === 0;
54 }
55 /**
56 * Ends the $haystack string with the suffix $needle?
57 */
58 public static function endsWith(string $haystack, string $needle): bool
59 {
60 return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
61 }
62 /**
63 * Does $haystack contain $needle?
64 */
65 public static function contains(string $haystack, string $needle): bool
66 {
67 return strpos($haystack, $needle) !== \false;
68 }
69 /**
70 * Returns a part of UTF-8 string specified by starting position and length. If start is negative,
71 * the returned string will start at the start'th character from the end of string.
72 */
73 public static function substring(string $s, int $start, ?int $length = null): string
74 {
75 if (function_exists('mb_substr')) {
76 return mb_substr($s, $start, $length, 'UTF-8');
77 // MB is much faster
78 } elseif (!extension_loaded('iconv')) {
79 throw new Nette\NotSupportedException(__METHOD__ . '() requires extension ICONV or MBSTRING, neither is loaded.');
80 } elseif ($length === null) {
81 $length = self::length($s);
82 } elseif ($start < 0 && $length < 0) {
83 $start += self::length($s);
84 // unifies iconv_substr behavior with mb_substr
85 }
86 return iconv_substr($s, $start, $length, 'UTF-8');
87 }
88 /**
89 * Removes control characters, normalizes line breaks to `\n`, removes leading and trailing blank lines,
90 * trims end spaces on lines, normalizes UTF-8 to the normal form of NFC.
91 */
92 public static function normalize(string $s): string
93 {
94 // convert to compressed normal form (NFC)
95 if (class_exists('Normalizer', \false) && ($n = \Normalizer::normalize($s, \Normalizer::FORM_C)) !== \false) {
96 $s = $n;
97 }
98 $s = self::normalizeNewLines($s);
99 // remove control characters; leave \t + \n
100 $s = self::pcre('preg_replace', ['#[\x00-\x08\x0B-\x1F\x7F-\x9F]+#u', '', $s]);
101 // right trim
102 $s = self::pcre('preg_replace', ['#[\t ]+$#m', '', $s]);
103 // leading and trailing blank lines
104 $s = trim($s, "\n");
105 return $s;
106 }
107 /**
108 * Standardize line endings to unix-like.
109 */
110 public static function normalizeNewLines(string $s): string
111 {
112 return str_replace(["\r\n", "\r"], "\n", $s);
113 }
114 /**
115 * Converts UTF-8 string to ASCII, ie removes diacritics etc.
116 */
117 public static function toAscii(string $s): string
118 {
119 $iconv = defined('ICONV_IMPL') ? trim(\ICONV_IMPL, '"\'') : null;
120 static $transliterator = null;
121 if ($transliterator === null) {
122 if (class_exists('Transliterator', \false)) {
123 $transliterator = \Transliterator::create('Any-Latin; Latin-ASCII');
124 } else {
125 trigger_error(__METHOD__ . "(): it is recommended to enable PHP extensions 'intl'.", \E_USER_NOTICE);
126 $transliterator = \false;
127 }
128 }
129 // remove control characters and check UTF-8 validity
130 $s = self::pcre('preg_replace', ['#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]#u', '', $s]);
131 // transliteration (by Transliterator and iconv) is not optimal, replace some characters directly
132 $s = strtr($s, ["" => '"', "" => '"', "" => '"', "" => "'", "" => "'", "" => "'", "°" => '^', "Я" => 'Ya', "я" => 'ya', "Ю" => 'Yu', "ю" => 'yu', "Ä" => 'Ae', "Ö" => 'Oe', "Ü" => 'Ue', "" => 'Ss', "ä" => 'ae', "ö" => 'oe', "ü" => 'ue', "ß" => 'ss']);
133 // „ “ ” ‚ ‘ ’ ° Я я Ю ю Ä Ö Ü ẞ ä ö ü ß
134 if ($iconv !== 'libiconv') {
135 $s = strtr($s, ["®" => '(R)', "©" => '(c)', "" => '...', "«" => '<<', "»" => '>>', "£" => 'lb', "¥" => 'yen', "²" => '^2', "³" => '^3', "µ" => 'u', "¹" => '^1', "º" => 'o', "¿" => '?', "ˊ" => "'", "ˍ" => '_', "˝" => '"', "" => '', "" => 'EUR', "" => 'TM', "" => 'e', "" => '<-', "" => '^', "" => '->', "" => 'V', "" => '<->']);
136 // ® © … « » £ ¥ ² ³ µ ¹ º ¿ ˊ ˍ ˝ ` € ™ ℮ ← ↑ → ↓ ↔
137 }
138 if ($transliterator) {
139 $s = $transliterator->transliterate($s);
140 // use iconv because The transliterator leaves some characters out of ASCII, eg → ʾ
141 if ($iconv === 'glibc') {
142 $s = strtr($s, '?', "\x01");
143 // temporarily hide ? to distinguish them from the garbage that iconv creates
144 $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
145 $s = str_replace(['?', "\x01"], ['', '?'], $s);
146 // remove garbage and restore ? characters
147 } elseif ($iconv === 'libiconv') {
148 $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
149 } else {
150 // null or 'unknown' (#216)
151 $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]);
152 // remove non-ascii chars
153 }
154 } elseif ($iconv === 'glibc' || $iconv === 'libiconv') {
155 // temporarily hide these characters to distinguish them from the garbage that iconv creates
156 $s = strtr($s, '`\'"^~?', "\x01\x02\x03\x04\x05\x06");
157 if ($iconv === 'glibc') {
158 // glibc implementation is very limited. transliterate into Windows-1250 and then into ASCII, so most Eastern European characters are preserved
159 $s = iconv('UTF-8', 'WINDOWS-1250//TRANSLIT//IGNORE', $s);
160 $s = strtr($s, "\xa5\xa3\xbc\x8c\xa7\x8a\xaa\x8d\x8f\x8e\xaf\xb9\xb3\xbe\x9c\x9a\xba\x9d\x9f\x9e\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\x96\xa0\x8b\x97\x9b\xa6\xad\xb7", 'ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt- <->|-.');
161 $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]);
162 } else {
163 $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
164 }
165 // remove garbage that iconv creates during transliteration (eg Ý -> Y')
166 $s = str_replace(['`', "'", '"', '^', '~', '?'], '', $s);
167 // restore temporarily hidden characters
168 $s = strtr($s, "\x01\x02\x03\x04\x05\x06", '`\'"^~?');
169 } else {
170 $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]);
171 // remove non-ascii chars
172 }
173 return $s;
174 }
175 /**
176 * Modifies the UTF-8 string to the form used in the URL, ie removes diacritics and replaces all characters
177 * except letters of the English alphabet and numbers with a hyphens.
178 */
179 public static function webalize(string $s, ?string $charlist = null, bool $lower = \true): string
180 {
181 $s = self::toAscii($s);
182 if ($lower) {
183 $s = strtolower($s);
184 }
185 $s = self::pcre('preg_replace', ['#[^a-z0-9' . (($charlist !== null) ? preg_quote($charlist, '#') : '') . ']+#i', '-', $s]);
186 $s = trim($s, '-');
187 return $s;
188 }
189 /**
190 * Truncates a UTF-8 string to given maximal length, while trying not to split whole words. Only if the string is truncated,
191 * an ellipsis (or something else set with third argument) is appended to the string.
192 */
193 public static function truncate(string $s, int $maxLen, string $append = ""): string
194 {
195 if (self::length($s) > $maxLen) {
196 $maxLen -= self::length($append);
197 if ($maxLen < 1) {
198 return $append;
199 } elseif ($matches = self::match($s, '#^.{1,' . $maxLen . '}(?=[\s\x00-/:-@\[-`{-~])#us')) {
200 return $matches[0] . $append;
201 } else {
202 return self::substring($s, 0, $maxLen) . $append;
203 }
204 }
205 return $s;
206 }
207 /**
208 * Indents a multiline text from the left. Second argument sets how many indentation chars should be used,
209 * while the indent itself is the third argument (*tab* by default).
210 */
211 public static function indent(string $s, int $level = 1, string $chars = "\t"): string
212 {
213 if ($level > 0) {
214 $s = self::replace($s, '#(?:^|[\r\n]+)(?=[^\r\n])#', '$0' . str_repeat($chars, $level));
215 }
216 return $s;
217 }
218 /**
219 * Converts all characters of UTF-8 string to lower case.
220 */
221 public static function lower(string $s): string
222 {
223 return mb_strtolower($s, 'UTF-8');
224 }
225 /**
226 * Converts the first character of a UTF-8 string to lower case and leaves the other characters unchanged.
227 */
228 public static function firstLower(string $s): string
229 {
230 return self::lower(self::substring($s, 0, 1)) . self::substring($s, 1);
231 }
232 /**
233 * Converts all characters of a UTF-8 string to upper case.
234 */
235 public static function upper(string $s): string
236 {
237 return mb_strtoupper($s, 'UTF-8');
238 }
239 /**
240 * Converts the first character of a UTF-8 string to upper case and leaves the other characters unchanged.
241 */
242 public static function firstUpper(string $s): string
243 {
244 return self::upper(self::substring($s, 0, 1)) . self::substring($s, 1);
245 }
246 /**
247 * Converts the first character of every word of a UTF-8 string to upper case and the others to lower case.
248 */
249 public static function capitalize(string $s): string
250 {
251 return mb_convert_case($s, \MB_CASE_TITLE, 'UTF-8');
252 }
253 /**
254 * Compares two UTF-8 strings or their parts, without taking character case into account. If length is null, whole strings are compared,
255 * if it is negative, the corresponding number of characters from the end of the strings is compared,
256 * otherwise the appropriate number of characters from the beginning is compared.
257 */
258 public static function compare(string $left, string $right, ?int $length = null): bool
259 {
260 if (class_exists('Normalizer', \false)) {
261 $left = \Normalizer::normalize($left, \Normalizer::FORM_D);
262 // form NFD is faster
263 $right = \Normalizer::normalize($right, \Normalizer::FORM_D);
264 // form NFD is faster
265 }
266 if ($length < 0) {
267 $left = self::substring($left, $length, -$length);
268 $right = self::substring($right, $length, -$length);
269 } elseif ($length !== null) {
270 $left = self::substring($left, 0, $length);
271 $right = self::substring($right, 0, $length);
272 }
273 return self::lower($left) === self::lower($right);
274 }
275 /**
276 * Finds the common prefix of strings or returns empty string if the prefix was not found.
277 * @param string[] $strings
278 */
279 public static function findPrefix(array $strings): string
280 {
281 $first = array_shift($strings);
282 for ($i = 0; $i < strlen($first); $i++) {
283 foreach ($strings as $s) {
284 if (!isset($s[$i]) || $first[$i] !== $s[$i]) {
285 while ($i && $first[$i - 1] >= "\x80" && $first[$i] >= "\x80" && $first[$i] < "\xc0") {
286 $i--;
287 }
288 return substr($first, 0, $i);
289 }
290 }
291 }
292 return $first;
293 }
294 /**
295 * Returns number of characters (not bytes) in UTF-8 string.
296 * That is the number of Unicode code points which may differ from the number of graphemes.
297 */
298 public static function length(string $s): int
299 {
300 return function_exists('mb_strlen') ? mb_strlen($s, 'UTF-8') : strlen(utf8_decode($s));
301 }
302 /**
303 * Removes all left and right side spaces (or the characters passed as second argument) from a UTF-8 encoded string.
304 */
305 public static function trim(string $s, string $charlist = self::TRIM_CHARACTERS): string
306 {
307 $charlist = preg_quote($charlist, '#');
308 return self::replace($s, '#^[' . $charlist . ']+|[' . $charlist . ']+$#Du', '');
309 }
310 /**
311 * Pads a UTF-8 string to given length by prepending the $pad string to the beginning.
312 * @param non-empty-string $pad
313 */
314 public static function padLeft(string $s, int $length, string $pad = ' '): string
315 {
316 $length = max(0, $length - self::length($s));
317 $padLen = self::length($pad);
318 return str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen) . $s;
319 }
320 /**
321 * Pads UTF-8 string to given length by appending the $pad string to the end.
322 * @param non-empty-string $pad
323 */
324 public static function padRight(string $s, int $length, string $pad = ' '): string
325 {
326 $length = max(0, $length - self::length($s));
327 $padLen = self::length($pad);
328 return $s . str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen);
329 }
330 /**
331 * Reverses UTF-8 string.
332 */
333 public static function reverse(string $s): string
334 {
335 if (!extension_loaded('iconv')) {
336 throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
337 }
338 return iconv('UTF-32LE', 'UTF-8', strrev(iconv('UTF-8', 'UTF-32BE', $s)));
339 }
340 /**
341 * Returns part of $haystack before $nth occurence of $needle or returns null if the needle was not found.
342 * Negative value means searching from the end.
343 */
344 public static function before(string $haystack, string $needle, int $nth = 1): ?string
345 {
346 $pos = self::pos($haystack, $needle, $nth);
347 return ($pos === null) ? null : substr($haystack, 0, $pos);
348 }
349 /**
350 * Returns part of $haystack after $nth occurence of $needle or returns null if the needle was not found.
351 * Negative value means searching from the end.
352 */
353 public static function after(string $haystack, string $needle, int $nth = 1): ?string
354 {
355 $pos = self::pos($haystack, $needle, $nth);
356 return ($pos === null) ? null : substr($haystack, $pos + strlen($needle));
357 }
358 /**
359 * Returns position in characters of $nth occurence of $needle in $haystack or null if the $needle was not found.
360 * Negative value of `$nth` means searching from the end.
361 */
362 public static function indexOf(string $haystack, string $needle, int $nth = 1): ?int
363 {
364 $pos = self::pos($haystack, $needle, $nth);
365 return ($pos === null) ? null : self::length(substr($haystack, 0, $pos));
366 }
367 /**
368 * Returns position in characters of $nth occurence of $needle in $haystack or null if the needle was not found.
369 */
370 private static function pos(string $haystack, string $needle, int $nth = 1): ?int
371 {
372 if (!$nth) {
373 return null;
374 } elseif ($nth > 0) {
375 if ($needle === '') {
376 return 0;
377 }
378 $pos = 0;
379 while (($pos = strpos($haystack, $needle, $pos)) !== \false && --$nth) {
380 $pos++;
381 }
382 } else {
383 $len = strlen($haystack);
384 if ($needle === '') {
385 return $len;
386 } elseif ($len === 0) {
387 return null;
388 }
389 $pos = $len - 1;
390 while (($pos = strrpos($haystack, $needle, $pos - $len)) !== \false && ++$nth) {
391 $pos--;
392 }
393 }
394 return Helpers::falseToNull($pos);
395 }
396 /**
397 * Splits a string into array by the regular expression. Parenthesized expression in the delimiter are captured.
398 * Parameter $flags can be any combination of PREG_SPLIT_NO_EMPTY and PREG_OFFSET_CAPTURE flags.
399 */
400 public static function split(string $subject, #[Language('RegExp')] string $pattern, int $flags = 0): array
401 {
402 return self::pcre('preg_split', [$pattern, $subject, -1, $flags | \PREG_SPLIT_DELIM_CAPTURE]);
403 }
404 /**
405 * Checks if given string matches a regular expression pattern and returns an array with first found match and each subpattern.
406 * Parameter $flags can be any combination of PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags.
407 */
408 public static function match(string $subject, #[Language('RegExp')] string $pattern, int $flags = 0, int $offset = 0): ?array
409 {
410 if ($offset > strlen($subject)) {
411 return null;
412 }
413 return self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset]) ? $m : null;
414 }
415 /**
416 * Finds all occurrences matching regular expression pattern and returns a two-dimensional array. Result is array of matches (ie uses by default PREG_SET_ORDER).
417 * Parameter $flags can be any combination of PREG_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL and PREG_PATTERN_ORDER flags.
418 */
419 public static function matchAll(string $subject, #[Language('RegExp')] string $pattern, int $flags = 0, int $offset = 0): array
420 {
421 if ($offset > strlen($subject)) {
422 return [];
423 }
424 self::pcre('preg_match_all', [$pattern, $subject, &$m, ($flags & \PREG_PATTERN_ORDER) ? $flags : ($flags | \PREG_SET_ORDER), $offset]);
425 return $m;
426 }
427 /**
428 * Replaces all occurrences matching regular expression $pattern which can be string or array in the form `pattern => replacement`.
429 * @param string|array $pattern
430 * @param string|callable $replacement
431 */
432 public static function replace(string $subject, #[Language('RegExp')] $pattern, $replacement = '', int $limit = -1): string
433 {
434 if (is_object($replacement) || is_array($replacement)) {
435 if (!is_callable($replacement, \false, $textual)) {
436 throw new Nette\InvalidStateException("Callback '{$textual}' is not callable.");
437 }
438 return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit]);
439 } elseif (is_array($pattern) && is_string(key($pattern))) {
440 $replacement = array_values($pattern);
441 $pattern = array_keys($pattern);
442 }
443 return self::pcre('preg_replace', [$pattern, $replacement, $subject, $limit]);
444 }
445 /** @internal */
446 public static function pcre(string $func, array $args)
447 {
448 $res = Callback::invokeSafe($func, $args, function (string $message) use ($args): void {
449 // compile-time error, not detectable by preg_last_error
450 throw new RegexpException($message . ' in pattern: ' . implode(' or ', (array) $args[0]));
451 });
452 if (($code = preg_last_error()) && ($res === null || !in_array($func, ['preg_filter', 'preg_replace_callback', 'preg_replace'], \true))) {
453 throw new RegexpException((RegexpException::MESSAGES[$code] ?? 'Unknown error') . ' (pattern: ' . implode(' or ', (array) $args[0]) . ')', $code);
454 }
455 return $res;
456 }
457 }
458