-
Notifications
You must be signed in to change notification settings - Fork 690
Expand file tree
/
Copy pathStringHelper.php
More file actions
2786 lines (2475 loc) · 92.9 KB
/
StringHelper.php
File metadata and controls
2786 lines (2475 loc) · 92.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\helpers;
use BackedEnum;
use Craft;
use HTMLPurifier_Config;
use Illuminate\Support\Str;
use IteratorAggregate;
use LitEmoji\LitEmoji;
use Normalizer;
use Throwable;
use voku\helper\ASCII;
use yii\base\Exception;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
use const ENT_COMPAT;
/**
* This helper class provides various multi-byte aware string related manipulation and encoding methods.
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @author Nicolas Grekas <[email protected]>
* @author Hamid Sarfraz <http://pageconfig.com/>
* @author Lars Moelleken <http://www.moelleken.org/>
* @since 3.0.0
*/
class StringHelper extends \yii\helpers\StringHelper
{
public const UTF8 = 'UTF-8';
/**
* @since 3.0.37
*/
public const UUID_PATTERN = '[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-4[A-Za-z0-9]{3}-[89abAB][A-Za-z0-9]{3}-[A-Za-z0-9]{12}';
/**
* @var array Character mappings
* @see asciiCharMap()
*/
private static array $_asciiCharMaps;
/**
* @var string[]|false
* @see escapeShortcodes()
*/
private static array|false $_shortcodeEscapeMap;
/**
* Gets the substring after the first occurrence of a separator.
*
* @param string $str The string to search.
* @param string $separator The separator string.
* @param bool $caseSensitive Whether to enforce case-sensitivity.
* @return string The resulting string.
* @since 3.3.0
*/
public static function afterFirst(string $str, string $separator, bool $caseSensitive = true): string
{
if ($separator === '' || $str === '') {
return '';
}
$offset = $caseSensitive ? mb_strpos($str, $separator) : mb_stripos($str, $separator);
if ($offset === false) {
return '';
}
return mb_substr($str, $offset + mb_strlen($separator));
}
/**
* Gets the substring after the last occurrence of a separator.
*
* @param string $str The string to search.
* @param string $separator The separator string.
* @param bool $caseSensitive Whether to enforce case-sensitivity.
* @return string The resulting string.
* @since 3.3.0
*/
public static function afterLast(string $str, string $separator, bool $caseSensitive = true): string
{
if ($separator === '' || $str === '') {
return '';
}
$offset = $caseSensitive ? mb_strrpos($str, $separator) : mb_strripos($str, $separator);
if ($offset === false) {
return '';
}
return mb_substr($str, $offset + mb_strlen($separator));
}
/**
* Returns a new string with $append appended.
*
* @param string $str The initial un-appended string.
* @param string $append The string to append.
* @return string The newly appended string.
* @since 3.3.0
*/
public static function append(string $str, string $append): string
{
return $str . $append;
}
/**
* Returns a new string with a random string appended to it.
*
* @param string $str The initial un-appended string.
* @param int $length The length of the random string.
* @param string $possibleChars The possible random characters to append.
* @return string The newly appended string.
* @since 3.3.0
*/
public static function appendRandomString(string $str, int $length, string $possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'): string
{
return $str . static::randomStringWithChars($possibleChars, $length);
}
/**
* Returns a new string with a unique identifier appended to it.
*
* @param string $str The initial un-appended string.
* @param string $entropyExtra Extra entropy via a string or int value.
* @param bool $md5 Whether to return the unique identifier as a md5 hash.
* @return string The newly appended string.
* @since 3.3.0
*/
public static function appendUniqueIdentifier(string $str, string $entropyExtra = '', bool $md5 = true): string
{
try {
$randInt = random_int(0, mt_getrandmax());
} catch (Throwable) {
$randInt = mt_rand(0, mt_getrandmax());
}
$uniqueHelper = $randInt .
session_id() .
($_SERVER['REMOTE_ADDR'] ?? '') .
($_SERVER['SERVER_ADDR'] ?? '') .
$entropyExtra;
$uniqueString = uniqid($uniqueHelper, true);
if ($md5) {
return md5($uniqueString . $uniqueHelper);
}
return $uniqueString;
}
/**
* Returns ASCII character mappings, merging in any custom defined mappings
* from the <config5:customAsciiCharMappings> config setting.
*
* @param bool $flat Whether the mappings should be returned as a flat array (é => e)
* @param string|null $language Whether to include language-specific mappings (only applied if $flat is true)
* @return array The fully merged ASCII character mappings.
*/
public static function asciiCharMap(bool $flat = false, ?string $language = null): array
{
$key = $flat ? 'flat-' . ($language ?? '*') : '*';
if (isset(self::$_asciiCharMaps[$key])) {
return self::$_asciiCharMaps[$key];
}
$map = ASCII::charsArrayWithSingleLanguageValues(false, false);
if ($language !== null) {
/** @var ASCII::*_LANGUAGE_CODE $language */
$langSpecific = ASCII::charsArrayWithOneLanguage($language, false, false);
if ($langSpecific !== []) {
$map = array_merge($map, $langSpecific);
}
}
if ($flat) {
return self::$_asciiCharMaps[$key] = $map;
}
$byAscii = [];
foreach ($map as $char => $ascii) {
$byAscii[$ascii][] = $char;
}
return self::$_asciiCharMaps[$key] = $byAscii;
}
/**
* Returns the character at $index, with indexes starting at 0.
*
* @param string $str The initial string to search.
* @param int $index The position of the character.
* @return string The resulting character.
* @since 3.3.0
*/
public static function at(string $str, int $index): string
{
return mb_substr($str, $index, 1);
}
/**
* Gets the substring before the first occurrence of a separator.
*
* @param string $str The string to search.
* @param string $separator The separator string.
* @param bool $caseSensitive
* @return string The resulting string.
* @since 3.3.0
*/
public static function beforeFirst(string $str, string $separator, bool $caseSensitive = true): string
{
if ($separator === '' || $str === '') {
return '';
}
$offset = $caseSensitive ? mb_strpos($str, $separator) : mb_stripos($str, $separator);
if ($offset === false) {
return '';
}
return mb_substr($str, 0, $offset);
}
/**
* Gets the substring before the last occurrence of a separator.
*
* @param string $str The string to search.
* @param string $separator The separator string.
* @param bool $caseSensitive
* @return string The resulting string.
* @since 3.3.0
*/
public static function beforeLast(string $str, string $separator, bool $caseSensitive = true): string
{
if ($separator === '' || $str === '') {
return '';
}
$offset = $caseSensitive ? mb_strrpos($str, $separator) : mb_strripos($str, $separator);
if ($offset === false) {
return '';
}
return mb_substr($str, 0, $offset);
}
/**
* Returns the substring between $start and $end, if found, or an empty string.
* An optional offset may be supplied from which to begin the search for the start string.
*
* @param string $str The string to search.
* @param string $start Delimiter marking the start of the substring.
* @param string $end Delimiter marking the end of the substring.
* @param int|null $offset Index from which to begin the search. Defaults to 0.
* @return string The resulting string.
*/
public static function between(string $str, string $start, string $end, ?int $offset = null): string
{
$startPos = mb_strpos($str, $start, $offset);
if ($startPos === false) {
return '';
}
$substrIndex = $startPos + mb_strlen($start);
$endPos = mb_strpos($str, $end, $substrIndex);
if ($endPos === false || $endPos === $substrIndex) {
return '';
}
return mb_substr($str, $substrIndex, $endPos - $substrIndex);
}
/**
* Returns a camelCase version of the given string. Trims surrounding spaces, capitalizes letters following digits,
* spaces, dashes and underscores, and removes spaces, dashes, as well as underscores.
*
* @param string $str The string to convert to camelCase.
* @return string The string in camelCase.
*/
public static function camelCase(string $str): string
{
return Str::camel($str);
}
/**
* Returns the string with the first letter of each word capitalized.
*
* @param string $str The string to parse.
* @return string The string with personal names capitalized.
* @since 3.3.0
* @deprecated in 5.9.0. Use [[toPascalCase()]] instead.
*/
public static function capitalizePersonalName(string $str): string
{
return static::toPascalCase($str);
}
/**
* Returns an array consisting of the characters in the string.
*
* @param string $str
* @return string[] An array of string chars
*/
public static function charsAsArray(string $str): array
{
return mb_str_split($str);
}
/**
* Trims the string and replaces consecutive whitespace characters with a single space. This includes tabs and
* newline characters, as well as multibyte whitespace such as the thin space and ideographic space.
*
* @param string $str The string to remove the whitespace from.
* @return string The trimmed string with condensed whitespace.
*/
public static function collapseWhitespace(string $str): string
{
return trim(mb_ereg_replace('[[:space:]]+', ' ', $str));
}
/**
* Returns true if the string contains $needle, false otherwise. By default, the comparison is case-sensitive, but
* can be made insensitive by setting $caseSensitive to false.
*
* @param string $haystack The string being checked.
* @param string $needle The substring to look for.
* @param bool $caseSensitive Whether to force case-sensitivity.
* @return bool Whether $haystack contains $needle.
*/
public static function contains(string $haystack, string $needle, bool $caseSensitive = true): bool
{
if (!$caseSensitive) {
// mb_strtolower() isn't as reliable on PHP 8.2
$haystack = mb_strtoupper($haystack);
$needle = mb_strtoupper($needle);
}
return str_contains($haystack, $needle);
}
/**
* Detects whether the given string has any 4-byte UTF-8 characters.
*
* @param string $str The string to process.
* @return bool Whether the string contains any 4-byte UTF-8 characters or not.
*/
public static function containsMb4(string $str): bool
{
$length = strlen($str);
for ($i = 0; $i < $length; $i++) {
if (ord($str[$i]) >= 240) {
return true;
}
}
return false;
}
/**
* Returns true if the string contains all $needles, false otherwise. By default, the comparison is case-sensitive,
* but can be made insensitive by setting $caseSensitive to false.
*
* @param string $haystack The string being checked.
* @param string[] $needles The substrings to look for.
* @param bool $caseSensitive Whether to force case-sensitivity.
* @return bool Whether $haystack contains all $needles.
*/
public static function containsAll(string $haystack, array $needles, bool $caseSensitive = true): bool
{
if (empty($needles)) {
return false;
}
foreach ($needles as $needle) {
if (!static::contains($haystack, $needle, $caseSensitive)) {
return false;
}
}
return true;
}
/**
* Returns true if the string contains any $needles, false otherwise. By default, the comparison is case-sensitive,
* but can be made insensitive by setting $caseSensitive to false.
*
* @param string $haystack The string being checked.
* @param string[] $needles The substrings to look for.
* @param bool $caseSensitive Whether to force case-sensitivity.
* @return bool Whether $haystack contains any $needles.
*/
public static function containsAny(string $haystack, array $needles, bool $caseSensitive = true): bool
{
foreach ($needles as $needle) {
if (static::contains($haystack, $needle, $caseSensitive)) {
return true;
}
}
return false;
}
/**
* Attempts to convert a string to UTF-8 and clean any non-valid UTF-8 characters.
*
* @param string $str
* @return string
*/
public static function convertToUtf8(string $str): string
{
// If it's already a UTF8 string, just clean and return it
if (static::isUtf8($str)) {
return HtmlPurifier::cleanUtf8($str);
}
// Otherwise set HTMLPurifier to the actual string encoding
$config = HTMLPurifier_Config::createDefault();
$config->set('Core.Encoding', static::encoding($str));
// Clean it
$str = HtmlPurifier::cleanUtf8($str);
// Convert it to UTF8 if possible
if (App::checkForValidIconv()) {
$str = HtmlPurifier::convertToUtf8($str, $config);
} else {
$str = mb_convert_encoding($str, self::UTF8);
}
return $str;
}
/**
* Converts line breaks to Unix line breaks (LF) within the given string.
*
* @param string $str
* @return string
* @since 5.9.0
*/
public static function convertLineBreaks(string $str): string
{
return preg_replace('/\R/u', "\n", $str);
}
/**
* Returns the length of the string, implementing the countable interface.
*
* @param string $str The string to count.
* @return int The length of the string.
* @since 3.3.0
*/
public static function count(string $str): int
{
return mb_strlen($str);
}
/**
* Returns the number of occurrences of $substring in the given string. By default, the comparison is case-sensitive,
* but can be made insensitive by setting $caseSensitive to false.
*
* @param string $str The string to search through.
* @param string $substring The substring to search for.
* @param bool $caseSensitive Whether to enforce case-sensitivity
* @return int The number of $substring occurrences.
*/
public static function countSubstrings(string $str, string $substring, bool $caseSensitive = true): int
{
if (!$caseSensitive) {
// mb_strtolower() isn't as reliable on PHP 8.2
$str = mb_strtoupper($str);
$substring = mb_strtoupper($substring);
}
return mb_substr_count($str, $substring);
}
/**
* Returns a lowercase and trimmed string separated by dashes. Dashes are
* inserted before uppercase characters (with the exception of the first
* character of the string), and in place of spaces as well as underscores.
*
* @param string $str The string to dasherize.
* @return string The dasherized string.
* @since 3.3.0
*/
public static function dasherize(string $str): string
{
return static::delimit($str, '-');
}
/**
* Base64-decodes and decrypts a string generated by [[encenc()]].
*
* @param string $str The string.
* @return string
* @throws InvalidConfigException on OpenSSL not loaded
* @throws Exception on OpenSSL error
*/
public static function decdec(string $str): string
{
if (str_starts_with($str, 'base64:')) {
$str = base64_decode(substr($str, 7));
}
if (str_starts_with($str, 'crypt:')) {
$str = Craft::$app->getSecurity()->decryptByKey(substr($str, 6));
}
return $str;
}
/**
* Returns a lowercase and trimmed string separated by the given delimiter. Delimiters are inserted before
* uppercase characters (with the exception of the first character of the string), and in place of spaces,
* dashes, and underscores. Alpha delimiters are not converted to lowercase.
*
* @param string $str The string to delimit.
* @param string $delimiter Sequence used to separate parts of the string
* @return string The delimited string.
*/
public static function delimit(string $str, string $delimiter): string
{
$str = (string) mb_ereg_replace('\\B(\\p{Lu})', '-\1', trim($str));
return mb_ereg_replace('[\\-_\\s]+', $delimiter, mb_strtolower($str));
}
/**
* Encrypts and base64-encodes a string.
*
* @param string $str the string
* @return string
* @throws InvalidConfigException on OpenSSL not loaded
* @throws Exception on OpenSSL error
* @see decdec()
*/
public static function encenc(string $str): string
{
return 'base64:' . base64_encode('crypt:' . Craft::$app->getSecurity()->encryptByKey($str));
}
/**
* HTML-encodes any 4-byte UTF-8 characters.
*
* @param string $str The string
* @return string The string with converted 4-byte UTF-8 characters
* @see http://stackoverflow.com/a/16496730/1688568
*/
public static function encodeMb4(string $str): string
{
// (Logic pulled from WP's wp_encode_emoji() function)
// UTF-32's hex encoding is the same as HTML's hex encoding.
// So, by converting from UTF-8 to UTF-32, we magically
// get the correct hex encoding.
return static::replaceMb4($str, static function($char) {
$unpacked = unpack('H*', mb_convert_encoding($char, 'UTF-32', self::UTF8));
return isset($unpacked[1]) ? '&#x' . ltrim($unpacked[1], '0') . ';' : '';
});
}
/**
* Gets the encoding of the given string.
*
* @param string $str The string to process.
* @return string The encoding of the string.
*/
public static function encoding(string $str): string
{
return mb_strtolower(mb_detect_encoding($str, mb_detect_order(), true));
}
/**
* Returns true if the string ends with any of $substrings, false otherwise.
* By default, the comparison is case-sensitive, but can be made insensitive
* by setting $caseSensitive to false.
*
* @param string $str The string to check the end of.
* @param string[] $substrings Substrings to look for.
* @param bool $caseSensitive Whether to force case-sensitivity.
* @return bool Whether $str ends with $substring.
* @since 3.3.0
*/
public static function endsWithAny(string $str, array $substrings, bool $caseSensitive = true): bool
{
if ($substrings === []) {
return false;
}
foreach ($substrings as $substring) {
if (static::endsWith($str, $substring, $caseSensitive)) {
return true;
}
}
return false;
}
/**
* Ensures that the string begins with $substring. If it doesn't, it's prepended.
*
* @param string $str The string to modify.
* @param string $substring The substring to add if not present.
* @return string The string prefixed by the $substring.
*/
public static function ensureLeft(string $str, string $substring): string
{
if (str_starts_with($str, $substring)) {
return $str;
}
return $substring . $str;
}
/**
* Ensures that the string ends with $substring. If it doesn't, it's appended.
*
* @param string $str The string to modify.
* @param string $substring The substring to add if not present.
* @return string The string suffixed by the $substring.
*/
public static function ensureRight(string $str, string $substring): string
{
if (str_ends_with($str, $substring)) {
return $str;
}
return $str . $substring;
}
/**
* Create a escape html version of the string via "$this->utf8::htmlspecialchars()".
*
* @param string $str The string to modify.
* @return string The string to escape.
* @since 3.3.0
*/
public static function escape(string $str): string
{
return htmlspecialchars($str);
}
/**
* Create an extract from a sentence, so if the search-string was found, it try to centered in the output.
*
* @param string $str The source string.
* @param string $search The string to search for.
* @param int|null $length By default, the length of the text divided by two.
* @param string $replacerForSkippedText The string to use for skipped text.
* @return string The string to escape.
* @since 3.3.0
*/
public static function extractText(string $str, string $search = '', ?int $length = null, string $replacerForSkippedText = '…'): string
{
if ($str === '') {
return '';
}
$trimChars = "\t\r\n -_()!~?=+/*\\,.:;\"'[]{}`&";
if ($length === null) {
$length = round(mb_strlen($str) / 2);
}
if ($search === '') {
if ($length > 0) {
$stringLength = mb_strlen($str);
$end = ($length - 1) > $stringLength ? $stringLength : ($length - 1);
} else {
$end = 0;
}
$pos = min(
mb_strpos($str, ' ', $end),
mb_strpos($str, '.', $end),
);
if ($pos) {
$strSub = mb_substr($str, 0, $pos);
if ($strSub === '') {
return '';
}
return rtrim($strSub, $trimChars) . $replacerForSkippedText;
}
return $str;
}
$wordPosition = mb_stripos($str, $search);
$halfSide = (int) ($wordPosition - $length / 2 + mb_strlen($search) / 2);
$posStart = 0;
if ($halfSide > 0) {
$halfText = mb_substr($str, 0, $halfSide);
if ($halfText !== '') {
$posStart = max(
mb_strrpos($halfText, ' '),
mb_strrpos($halfText, '.'),
);
}
}
if ($wordPosition && $halfSide > 0) {
$offset = $posStart + $length - 1;
$real_length = mb_strlen($str);
if ($offset > $real_length) {
$offset = $real_length;
}
$posEnd = min(
mb_strpos($str, ' ', $offset),
mb_strpos($str, '.', $offset),
) - $posStart;
if (!$posEnd || $posEnd <= 0) {
$strSub = mb_substr($str, $posStart, mb_strlen($str));
if ($strSub !== '') {
$extract = $replacerForSkippedText . ltrim($strSub, $trimChars);
} else {
$extract = '';
}
} else {
$strSub = mb_substr($str, $posStart, $posEnd);
$extract = $replacerForSkippedText . trim($strSub, $trimChars) . $replacerForSkippedText;
}
} else {
$offset = $length - 1;
$trueLength = mb_strlen($str);
if ($offset > $trueLength) {
$offset = $trueLength;
}
$posEnd = min(
mb_strpos($str, ' ', $offset),
mb_strpos($str, '.', $offset),
);
if ($posEnd) {
$strSub = mb_substr($str, 0, $posEnd);
$extract = rtrim($strSub, $trimChars) . $replacerForSkippedText;
} else {
$extract = $str;
}
}
return $extract;
}
/**
* Returns the first $n characters of the string.
*
* @param string $str The string from which to get the substring.
* @param int $number The Number of chars to retrieve from the start.
* @return string The first $number characters.
*/
public static function first(string $str, int $number): string
{
if ($str === '' || $number <= 0) {
return '';
}
return mb_substr($str, 0, $number);
}
/**
* Returns whether the given string has any lowercase characters in it.
*
* @param string $str The string to check.
* @return bool If the string has a lowercase character or not.
*/
public static function hasLowerCase(string $str): bool
{
return mb_ereg_match('.*[[:lower:]]', $str);
}
/**
* Returns whether the given string has any uppercase characters in it.
*
* @param string $str The string to check.
* @return bool If the string has an uppercase character or not.
*/
public static function hasUpperCase(string $str): bool
{
return mb_ereg_match('.*[[:upper:]]', $str);
}
/**
* Convert all HTML entities to their applicable characters.
*
* @param string $str The string to process.
* @param int $flags A bitmask of these flags: https://www.php.net/manual/en/function.html-entity-decode.php
* @return string The decoded string.
* @since 3.3.0
*/
public static function htmlDecode(string $str, int $flags = ENT_COMPAT): string
{
if (!isset($str[3]) || !str_contains($str, '&')) {
return $str;
}
do {
$strCompare = $str;
if (str_contains($str, '&')) {
if (str_contains($str, '&#')) {
$str = (string) preg_replace('/(&#(?:x0*[0-9a-fA-F]{2,6}(?![0-9a-fA-F;])|(?:0*\d{2,6}(?![0-9;]))))/S', '$1;', $str);
}
$str = html_entity_decode($str, $flags, 'UTF-8');
}
} while ($strCompare !== $str);
return $str;
}
/**
* Convert all applicable characters to HTML entities.
*
* @param string $str The string to process.
* @param int $flags A bitmask of these flags: https://www.php.net/manual/en/function.html-entity-encode.php
* @return string The encoded string.
* @since 3.3.0
*/
public static function htmlEncode(string $str, int $flags = ENT_COMPAT): string
{
return htmlentities($str, $flags, 'UTF-8');
}
/**
* Capitalizes the first word of the string, replaces underscores with
* spaces, and strips '_id'.
*
* @param string $str The string to process.
* @return string The humanized string.
* @since 3.3.0
*/
public static function humanize(string $str): string
{
$str = str_replace(['_id', '_'], ['', ' '], $str);
return static::upperCaseFirst(trim($str));
}
/**
* Returns the index of the first occurrence of $needle in the string, and false if not found.
* Accepts an optional offset from which to begin the search.
*
* @param string $str The string to check the index of.
* @param string $needle The substring to look for.
* @param int $offset The offset from which to search.
* @param bool $caseSensitive Whether to perform a case-sensitive search or not.
* @return int|false The occurrence's index if found, otherwise false.
*/
public static function indexOf(string $str, string $needle, int $offset = 0, bool $caseSensitive = true): int|false
{
if ($str === '' && $needle === '') {
return 0;
}
if ($caseSensitive) {
return mb_strpos($str, $needle, $offset);
}
return mb_stripos($str, $needle, $offset);
}
/**
* Returns the index of the last occurrence of $needle in the string,
* and false if not found. Accepts an optional offset from which to begin
* the search. Offsets may be negative to count from the last character
* in the string.
*
* @param string $str The string to check the last index of.
* @param string $needle The substring to look for.
* @param int $offset The offset from which to search.
* @param bool $caseSensitive Whether to perform a case-sensitive search or not.
* @return int|false The occurrence's last index if found, otherwise false.
*/
public static function indexOfLast(string $str, string $needle, int $offset = 0, bool $caseSensitive = true): int|false
{
if ($str === '' && $needle === '') {
return 0;
}
if ($caseSensitive) {
return mb_strrpos($str, $needle, $offset);
}
return mb_strripos($str, $needle, $offset);
}
/**
* Inserts $substring into the string at the $index provided.
*
* @param string $str The string to insert into.
* @param string $substring The string to be inserted.
* @param int $index The 0-based index at which to insert the substring.
* @return string The resulting string after the insertion
*/
public static function insert(string $str, string $substring, int $index): string
{
$len = mb_strlen($str);
if ($index > $len) {
return $str;
}
return mb_substr($str, 0, $index) .
$substring .
mb_substr($str, $index, $len);
}
/**
* Returns true if the string contains the $pattern, otherwise false.
*
* WARNING: Asterisks ("*") are translated into (".*") zero-or-more regular
* expression wildcards.
*
* @param string $str The string to process.
* @param string $pattern The string or pattern to match against.
* @return bool Whether we match the provided pattern.
* @since 3.3.0
*/
public static function is(string $str, string $pattern): bool
{
return Str::is($pattern, $str);
}
/**
* Returns true if the string contains only alphabetic chars, false otherwise.
*
* @param string $str The string to check.
* @return bool Whether $str contains only alphabetic chars.
*/
public static function isAlpha(string $str): bool
{
return mb_ereg_match('^[[:alpha:]]*$', $str);
}
/**
* Returns true if the string contains only alphabetic and numeric chars, false otherwise.
*
* @param string $str The string to check.
* @return bool Whether $str contains only alphanumeric chars.
*/
public static function isAlphanumeric(string $str): bool
{
return mb_ereg_match('^[[:alnum:]]*$', $str);
}
/**
* Returns true if the string is base64 encoded, false otherwise.
*
* @param string $str The string to check.
* @param bool $emptyStringIsValid Whether an empty string is considered valid.
* @return bool Whether $str is base64 encoded.
* @since 3.3.0
*/
public static function isBase64(string $str, bool $emptyStringIsValid = true): bool
{
if (!$emptyStringIsValid && $str === '') {
return false;
}
$base64String = base64_decode($str, true);
return $base64String !== false && base64_encode($base64String) === $str;
}
/**
* Returns true if the string contains only whitespace chars, false otherwise.
*
* @param string $str The string to check.
* @return bool Whether $str contains only whitespace characters.
* @since 3.3.0
*/
public static function isBlank(string $str): bool
{
return mb_ereg_match('^[[:space:]]*$', $str);
}
/**
* Returns true if the string contains only hexadecimal chars, false otherwise.
*
* @param string $str The string to check.
* @return bool Whether $str contains only hexadecimal chars.