Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 150 | Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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
 
8
declare(strict_types=1);
9
 
10
namespace Nette\Utils;
11
 
12
use Nette;
13
use function is_array, is_object, strlen;
14
 
15
 
16
/**
17
 * String tools library.
18
 */
19
class Strings
20
{
21
	use Nette\StaticClass;
22
 
23
	public const TRIM_CHARACTERS = " \t\n\r\0\x0B\u{A0}";
24
 
25
 
26
	/**
27
	 * Checks if the string is valid in UTF-8 encoding.
28
	 */
29
	public static function checkEncoding(string $s): bool
30
	{
31
		return $s === self::fixEncoding($s);
32
	}
33
 
34
 
35
	/**
36
	 * Removes all invalid UTF-8 characters from a string.
37
	 */
38
	public static function fixEncoding(string $s): string
39
	{
40
		// removes xD800-xDFFF, x110000 and higher
41
		return htmlspecialchars_decode(htmlspecialchars($s, ENT_NOQUOTES | ENT_IGNORE, 'UTF-8'), ENT_NOQUOTES);
42
	}
43
 
44
 
45
	/**
46
	 * Returns a specific character in UTF-8 from code point (number in range 0x0000..D7FF or 0xE000..10FFFF).
47
	 * @throws Nette\InvalidArgumentException if code point is not in valid range
48
	 */
49
	public static function chr(int $code): string
50
	{
51
		if ($code < 0 || ($code >= 0xD800 && $code <= 0xDFFF) || $code > 0x10FFFF) {
52
			throw new Nette\InvalidArgumentException('Code point must be in range 0x0 to 0xD7FF or 0xE000 to 0x10FFFF.');
53
		} elseif (!extension_loaded('iconv')) {
54
			throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
55
		}
56
 
57
		return iconv('UTF-32BE', 'UTF-8//IGNORE', pack('N', $code));
58
	}
59
 
60
 
61
	/**
62
	 * Starts the $haystack string with the prefix $needle?
63
	 */
64
	public static function startsWith(string $haystack, string $needle): bool
65
	{
66
		return strncmp($haystack, $needle, strlen($needle)) === 0;
67
	}
68
 
69
 
70
	/**
71
	 * Ends the $haystack string with the suffix $needle?
72
	 */
73
	public static function endsWith(string $haystack, string $needle): bool
74
	{
75
		return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
76
	}
77
 
78
 
79
	/**
80
	 * Does $haystack contain $needle?
81
	 */
82
	public static function contains(string $haystack, string $needle): bool
83
	{
84
		return strpos($haystack, $needle) !== false;
85
	}
86
 
87
 
88
	/**
89
	 * Returns a part of UTF-8 string specified by starting position and length. If start is negative,
90
	 * the returned string will start at the start'th character from the end of string.
91
	 */
92
	public static function substring(string $s, int $start, ?int $length = null): string
93
	{
94
		if (function_exists('mb_substr')) {
95
			return mb_substr($s, $start, $length, 'UTF-8'); // MB is much faster
96
		} elseif (!extension_loaded('iconv')) {
97
			throw new Nette\NotSupportedException(__METHOD__ . '() requires extension ICONV or MBSTRING, neither is loaded.');
98
		} elseif ($length === null) {
99
			$length = self::length($s);
100
		} elseif ($start < 0 && $length < 0) {
101
			$start += self::length($s); // unifies iconv_substr behavior with mb_substr
102
		}
103
 
104
		return iconv_substr($s, $start, $length, 'UTF-8');
105
	}
106
 
107
 
108
	/**
109
	 * Removes control characters, normalizes line breaks to `\n`, removes leading and trailing blank lines,
110
	 * trims end spaces on lines, normalizes UTF-8 to the normal form of NFC.
111
	 */
112
	public static function normalize(string $s): string
113
	{
114
		// convert to compressed normal form (NFC)
115
		if (class_exists('Normalizer', false) && ($n = \Normalizer::normalize($s, \Normalizer::FORM_C)) !== false) {
116
			$s = $n;
117
		}
118
 
119
		$s = self::normalizeNewLines($s);
120
 
121
		// remove control characters; leave \t + \n
122
		$s = self::pcre('preg_replace', ['#[\x00-\x08\x0B-\x1F\x7F-\x9F]+#u', '', $s]);
123
 
124
		// right trim
125
		$s = self::pcre('preg_replace', ['#[\t ]+$#m', '', $s]);
126
 
127
		// leading and trailing blank lines
128
		$s = trim($s, "\n");
129
 
130
		return $s;
131
	}
132
 
133
 
134
	/**
135
	 * Standardize line endings to unix-like.
136
	 */
137
	public static function normalizeNewLines(string $s): string
138
	{
139
		return str_replace(["\r\n", "\r"], "\n", $s);
140
	}
141
 
142
 
143
	/**
144
	 * Converts UTF-8 string to ASCII, ie removes diacritics etc.
145
	 */
146
	public static function toAscii(string $s): string
147
	{
148
		$iconv = defined('ICONV_IMPL') ? trim(ICONV_IMPL, '"\'') : null;
149
		static $transliterator = null;
150
		if ($transliterator === null) {
151
			if (class_exists('Transliterator', false)) {
152
				$transliterator = \Transliterator::create('Any-Latin; Latin-ASCII');
153
			} else {
154
				trigger_error(__METHOD__ . "(): it is recommended to enable PHP extensions 'intl'.", E_USER_NOTICE);
155
				$transliterator = false;
156
			}
157
		}
158
 
159
		// remove control characters and check UTF-8 validity
160
		$s = self::pcre('preg_replace', ['#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]#u', '', $s]);
161
 
162
		// transliteration (by Transliterator and iconv) is not optimal, replace some characters directly
163
		$s = strtr($s, ["\u{201E}" => '"', "\u{201C}" => '"', "\u{201D}" => '"', "\u{201A}" => "'", "\u{2018}" => "'", "\u{2019}" => "'", "\u{B0}" => '^', "\u{42F}" => 'Ya', "\u{44F}" => 'ya', "\u{42E}" => 'Yu', "\u{44E}" => 'yu', "\u{c4}" => 'Ae', "\u{d6}" => 'Oe', "\u{dc}" => 'Ue', "\u{1e9e}" => 'Ss', "\u{e4}" => 'ae', "\u{f6}" => 'oe', "\u{fc}" => 'ue', "\u{df}" => 'ss']); // „ “ ” ‚ ‘ ’ ° Я я Ю ю Ä Ö Ü ẞ ä ö ü ß
164
		if ($iconv !== 'libiconv') {
165
			$s = strtr($s, ["\u{AE}" => '(R)', "\u{A9}" => '(c)', "\u{2026}" => '...', "\u{AB}" => '<<', "\u{BB}" => '>>', "\u{A3}" => 'lb', "\u{A5}" => 'yen', "\u{B2}" => '^2', "\u{B3}" => '^3', "\u{B5}" => 'u', "\u{B9}" => '^1', "\u{BA}" => 'o', "\u{BF}" => '?', "\u{2CA}" => "'", "\u{2CD}" => '_', "\u{2DD}" => '"', "\u{1FEF}" => '', "\u{20AC}" => 'EUR', "\u{2122}" => 'TM', "\u{212E}" => 'e', "\u{2190}" => '<-', "\u{2191}" => '^', "\u{2192}" => '->', "\u{2193}" => 'V', "\u{2194}" => '<->']); // ® © … « » £ ¥ ² ³ µ ¹ º ¿ ˊ ˍ ˝ ` € ™ ℮ ← ↑ → ↓ ↔
166
		}
167
 
168
		if ($transliterator) {
169
			$s = $transliterator->transliterate($s);
170
			// use iconv because The transliterator leaves some characters out of ASCII, eg → ʾ
171
			if ($iconv === 'glibc') {
172
				$s = strtr($s, '?', "\x01"); // temporarily hide ? to distinguish them from the garbage that iconv creates
173
				$s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
174
				$s = str_replace(['?', "\x01"], ['', '?'], $s); // remove garbage and restore ? characters
175
			} elseif ($iconv === 'libiconv') {
176
				$s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
177
			} else { // null or 'unknown' (#216)
178
				$s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); // remove non-ascii chars
179
			}
180
		} elseif ($iconv === 'glibc' || $iconv === 'libiconv') {
181
			// temporarily hide these characters to distinguish them from the garbage that iconv creates
182
			$s = strtr($s, '`\'"^~?', "\x01\x02\x03\x04\x05\x06");
183
			if ($iconv === 'glibc') {
184
				// glibc implementation is very limited. transliterate into Windows-1250 and then into ASCII, so most Eastern European characters are preserved
185
				$s = iconv('UTF-8', 'WINDOWS-1250//TRANSLIT//IGNORE', $s);
186
				$s = strtr(
187
					$s,
188
					"\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",
189
					'ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt- <->|-.'
190
				);
191
				$s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]);
192
			} else {
193
				$s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
194
			}
195
 
196
			// remove garbage that iconv creates during transliteration (eg Ý -> Y')
197
			$s = str_replace(['`', "'", '"', '^', '~', '?'], '', $s);
198
			// restore temporarily hidden characters
199
			$s = strtr($s, "\x01\x02\x03\x04\x05\x06", '`\'"^~?');
200
		} else {
201
			$s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); // remove non-ascii chars
202
		}
203
 
204
		return $s;
205
	}
206
 
207
 
208
	/**
209
	 * Modifies the UTF-8 string to the form used in the URL, ie removes diacritics and replaces all characters
210
	 * except letters of the English alphabet and numbers with a hyphens.
211
	 */
212
	public static function webalize(string $s, ?string $charlist = null, bool $lower = true): string
213
	{
214
		$s = self::toAscii($s);
215
		if ($lower) {
216
			$s = strtolower($s);
217
		}
218
 
219
		$s = self::pcre('preg_replace', ['#[^a-z0-9' . ($charlist !== null ? preg_quote($charlist, '#') : '') . ']+#i', '-', $s]);
220
		$s = trim($s, '-');
221
		return $s;
222
	}
223
 
224
 
225
	/**
226
	 * Truncates a UTF-8 string to given maximal length, while trying not to split whole words. Only if the string is truncated,
227
	 * an ellipsis (or something else set with third argument) is appended to the string.
228
	 */
229
	public static function truncate(string $s, int $maxLen, string $append = "\u{2026}"): string
230
	{
231
		if (self::length($s) > $maxLen) {
232
			$maxLen -= self::length($append);
233
			if ($maxLen < 1) {
234
				return $append;
235
 
236
			} elseif ($matches = self::match($s, '#^.{1,' . $maxLen . '}(?=[\s\x00-/:-@\[-`{-~])#us')) {
237
				return $matches[0] . $append;
238
 
239
			} else {
240
				return self::substring($s, 0, $maxLen) . $append;
241
			}
242
		}
243
 
244
		return $s;
245
	}
246
 
247
 
248
	/**
249
	 * Indents a multiline text from the left. Second argument sets how many indentation chars should be used,
250
	 * while the indent itself is the third argument (*tab* by default).
251
	 */
252
	public static function indent(string $s, int $level = 1, string $chars = "\t"): string
253
	{
254
		if ($level > 0) {
255
			$s = self::replace($s, '#(?:^|[\r\n]+)(?=[^\r\n])#', '$0' . str_repeat($chars, $level));
256
		}
257
 
258
		return $s;
259
	}
260
 
261
 
262
	/**
263
	 * Converts all characters of UTF-8 string to lower case.
264
	 */
265
	public static function lower(string $s): string
266
	{
267
		return mb_strtolower($s, 'UTF-8');
268
	}
269
 
270
 
271
	/**
272
	 * Converts the first character of a UTF-8 string to lower case and leaves the other characters unchanged.
273
	 */
274
	public static function firstLower(string $s): string
275
	{
276
		return self::lower(self::substring($s, 0, 1)) . self::substring($s, 1);
277
	}
278
 
279
 
280
	/**
281
	 * Converts all characters of a UTF-8 string to upper case.
282
	 */
283
	public static function upper(string $s): string
284
	{
285
		return mb_strtoupper($s, 'UTF-8');
286
	}
287
 
288
 
289
	/**
290
	 * Converts the first character of a UTF-8 string to upper case and leaves the other characters unchanged.
291
	 */
292
	public static function firstUpper(string $s): string
293
	{
294
		return self::upper(self::substring($s, 0, 1)) . self::substring($s, 1);
295
	}
296
 
297
 
298
	/**
299
	 * Converts the first character of every word of a UTF-8 string to upper case and the others to lower case.
300
	 */
301
	public static function capitalize(string $s): string
302
	{
303
		return mb_convert_case($s, MB_CASE_TITLE, 'UTF-8');
304
	}
305
 
306
 
307
	/**
308
	 * Compares two UTF-8 strings or their parts, without taking character case into account. If length is null, whole strings are compared,
309
	 * if it is negative, the corresponding number of characters from the end of the strings is compared,
310
	 * otherwise the appropriate number of characters from the beginning is compared.
311
	 */
312
	public static function compare(string $left, string $right, ?int $length = null): bool
313
	{
314
		if (class_exists('Normalizer', false)) {
315
			$left = \Normalizer::normalize($left, \Normalizer::FORM_D); // form NFD is faster
316
			$right = \Normalizer::normalize($right, \Normalizer::FORM_D); // form NFD is faster
317
		}
318
 
319
		if ($length < 0) {
320
			$left = self::substring($left, $length, -$length);
321
			$right = self::substring($right, $length, -$length);
322
		} elseif ($length !== null) {
323
			$left = self::substring($left, 0, $length);
324
			$right = self::substring($right, 0, $length);
325
		}
326
 
327
		return self::lower($left) === self::lower($right);
328
	}
329
 
330
 
331
	/**
332
	 * Finds the common prefix of strings or returns empty string if the prefix was not found.
333
	 * @param  string[]  $strings
334
	 */
335
	public static function findPrefix(array $strings): string
336
	{
337
		$first = array_shift($strings);
338
		for ($i = 0; $i < strlen($first); $i++) {
339
			foreach ($strings as $s) {
340
				if (!isset($s[$i]) || $first[$i] !== $s[$i]) {
341
					while ($i && $first[$i - 1] >= "\x80" && $first[$i] >= "\x80" && $first[$i] < "\xC0") {
342
						$i--;
343
					}
344
 
345
					return substr($first, 0, $i);
346
				}
347
			}
348
		}
349
 
350
		return $first;
351
	}
352
 
353
 
354
	/**
355
	 * Returns number of characters (not bytes) in UTF-8 string.
356
	 * That is the number of Unicode code points which may differ from the number of graphemes.
357
	 */
358
	public static function length(string $s): int
359
	{
360
		return function_exists('mb_strlen')
361
			? mb_strlen($s, 'UTF-8')
362
			: strlen(utf8_decode($s));
363
	}
364
 
365
 
366
	/**
367
	 * Removes all left and right side spaces (or the characters passed as second argument) from a UTF-8 encoded string.
368
	 */
369
	public static function trim(string $s, string $charlist = self::TRIM_CHARACTERS): string
370
	{
371
		$charlist = preg_quote($charlist, '#');
372
		return self::replace($s, '#^[' . $charlist . ']+|[' . $charlist . ']+$#Du', '');
373
	}
374
 
375
 
376
	/**
377
	 * Pads a UTF-8 string to given length by prepending the $pad string to the beginning.
378
	 */
379
	public static function padLeft(string $s, int $length, string $pad = ' '): string
380
	{
381
		$length = max(0, $length - self::length($s));
382
		$padLen = self::length($pad);
383
		return str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen) . $s;
384
	}
385
 
386
 
387
	/**
388
	 * Pads UTF-8 string to given length by appending the $pad string to the end.
389
	 */
390
	public static function padRight(string $s, int $length, string $pad = ' '): string
391
	{
392
		$length = max(0, $length - self::length($s));
393
		$padLen = self::length($pad);
394
		return $s . str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen);
395
	}
396
 
397
 
398
	/**
399
	 * Reverses UTF-8 string.
400
	 */
401
	public static function reverse(string $s): string
402
	{
403
		if (!extension_loaded('iconv')) {
404
			throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
405
		}
406
 
407
		return iconv('UTF-32LE', 'UTF-8', strrev(iconv('UTF-8', 'UTF-32BE', $s)));
408
	}
409
 
410
 
411
	/**
412
	 * Returns part of $haystack before $nth occurence of $needle or returns null if the needle was not found.
413
	 * Negative value means searching from the end.
414
	 */
415
	public static function before(string $haystack, string $needle, int $nth = 1): ?string
416
	{
417
		$pos = self::pos($haystack, $needle, $nth);
418
		return $pos === null
419
			? null
420
			: substr($haystack, 0, $pos);
421
	}
422
 
423
 
424
	/**
425
	 * Returns part of $haystack after $nth occurence of $needle or returns null if the needle was not found.
426
	 * Negative value means searching from the end.
427
	 */
428
	public static function after(string $haystack, string $needle, int $nth = 1): ?string
429
	{
430
		$pos = self::pos($haystack, $needle, $nth);
431
		return $pos === null
432
			? null
433
			: substr($haystack, $pos + strlen($needle));
434
	}
435
 
436
 
437
	/**
438
	 * Returns position in characters of $nth occurence of $needle in $haystack or null if the $needle was not found.
439
	 * Negative value of `$nth` means searching from the end.
440
	 */
441
	public static function indexOf(string $haystack, string $needle, int $nth = 1): ?int
442
	{
443
		$pos = self::pos($haystack, $needle, $nth);
444
		return $pos === null
445
			? null
446
			: self::length(substr($haystack, 0, $pos));
447
	}
448
 
449
 
450
	/**
451
	 * Returns position in characters of $nth occurence of $needle in $haystack or null if the needle was not found.
452
	 */
453
	private static function pos(string $haystack, string $needle, int $nth = 1): ?int
454
	{
455
		if (!$nth) {
456
			return null;
457
		} elseif ($nth > 0) {
458
			if ($needle === '') {
459
				return 0;
460
			}
461
 
462
			$pos = 0;
463
			while (($pos = strpos($haystack, $needle, $pos)) !== false && --$nth) {
464
				$pos++;
465
			}
466
		} else {
467
			$len = strlen($haystack);
468
			if ($needle === '') {
469
				return $len;
470
			} elseif ($len === 0) {
471
				return null;
472
			}
473
 
474
			$pos = $len - 1;
475
			while (($pos = strrpos($haystack, $needle, $pos - $len)) !== false && ++$nth) {
476
				$pos--;
477
			}
478
		}
479
 
480
		return Helpers::falseToNull($pos);
481
	}
482
 
483
 
484
	/**
485
	 * Splits a string into array by the regular expression. Parenthesized expression in the delimiter are captured.
486
	 * Parameter $flags can be any combination of PREG_SPLIT_NO_EMPTY and PREG_OFFSET_CAPTURE flags.
487
	 */
488
	public static function split(string $subject, string $pattern, int $flags = 0): array
489
	{
490
		return self::pcre('preg_split', [$pattern, $subject, -1, $flags | PREG_SPLIT_DELIM_CAPTURE]);
491
	}
492
 
493
 
494
	/**
495
	 * Checks if given string matches a regular expression pattern and returns an array with first found match and each subpattern.
496
	 * Parameter $flags can be any combination of PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags.
497
	 */
498
	public static function match(string $subject, string $pattern, int $flags = 0, int $offset = 0): ?array
499
	{
500
		if ($offset > strlen($subject)) {
501
			return null;
502
		}
503
 
504
		return self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset])
505
			? $m
506
			: null;
507
	}
508
 
509
 
510
	/**
511
	 * 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).
512
	 * Parameter $flags can be any combination of PREG_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL and PREG_PATTERN_ORDER flags.
513
	 */
514
	public static function matchAll(string $subject, string $pattern, int $flags = 0, int $offset = 0): array
515
	{
516
		if ($offset > strlen($subject)) {
517
			return [];
518
		}
519
 
520
		self::pcre('preg_match_all', [
521
			$pattern, $subject, &$m,
522
			($flags & PREG_PATTERN_ORDER) ? $flags : ($flags | PREG_SET_ORDER),
523
			$offset,
524
		]);
525
		return $m;
526
	}
527
 
528
 
529
	/**
530
	 * Replaces all occurrences matching regular expression $pattern which can be string or array in the form `pattern => replacement`.
531
	 * @param  string|array  $pattern
532
	 * @param  string|callable  $replacement
533
	 */
534
	public static function replace(string $subject, $pattern, $replacement = '', int $limit = -1): string
535
	{
536
		if (is_object($replacement) || is_array($replacement)) {
537
			if (!is_callable($replacement, false, $textual)) {
538
				throw new Nette\InvalidStateException("Callback '$textual' is not callable.");
539
			}
540
 
541
			return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit]);
542
 
543
		} elseif (is_array($pattern) && is_string(key($pattern))) {
544
			$replacement = array_values($pattern);
545
			$pattern = array_keys($pattern);
546
		}
547
 
548
		return self::pcre('preg_replace', [$pattern, $replacement, $subject, $limit]);
549
	}
550
 
551
 
552
	/** @internal */
553
	public static function pcre(string $func, array $args)
554
	{
555
		$res = Callback::invokeSafe($func, $args, function (string $message) use ($args): void {
556
			// compile-time error, not detectable by preg_last_error
557
			throw new RegexpException($message . ' in pattern: ' . implode(' or ', (array) $args[0]));
558
		});
559
 
560
		if (($code = preg_last_error()) // run-time error, but preg_last_error & return code are liars
561
			&& ($res === null || !in_array($func, ['preg_filter', 'preg_replace_callback', 'preg_replace'], true))
562
		) {
563
			throw new RegexpException((RegexpException::MESSAGES[$code] ?? 'Unknown error')
564
				. ' (pattern: ' . implode(' or ', (array) $args[0]) . ')', $code);
565
		}
566
 
567
		return $res;
568
	}
569
}