-
Notifications
You must be signed in to change notification settings - Fork 217
/
Copy pathStringy.php
1986 lines (1746 loc) · 67.9 KB
/
Stringy.php
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
namespace Stringy;
use ArrayAccess;
use ArrayIterator;
use Countable;
use Exception;
use InvalidArgumentException;
use IteratorAggregate;
use OutOfBoundsException;
class Stringy implements Countable, IteratorAggregate, ArrayAccess
{
/**
* An instance's string.
*
* @var string
*/
protected $str;
/**
* The string's encoding, which should be one of the mbstring module's
* supported encodings.
*
* @var string
*/
protected $encoding;
/**
* Initializes a Stringy object and assigns both str and encoding properties
* the supplied values. $str is cast to a string prior to assignment, and if
* $encoding is not specified, it defaults to mb_internal_encoding(). Throws
* an InvalidArgumentException if the first argument is an array or object
* without a __toString method.
*
* @param mixed $str Value to modify, after being cast to string
* @param string $encoding The character encoding
* @throws \InvalidArgumentException if an array or object without a
* __toString method is passed as the first argument
*/
public function __construct($str = '', $encoding = null)
{
if (is_array($str)) {
throw new InvalidArgumentException(
'Passed value cannot be an array'
);
} elseif (is_object($str) && !method_exists($str, '__toString')) {
throw new InvalidArgumentException(
'Passed object must have a __toString method'
);
}
$this->str = (string) $str;
$this->encoding = $encoding ?: \mb_internal_encoding();
}
/**
* Creates a Stringy object and assigns both str and encoding properties
* the supplied values. $str is cast to a string prior to assignment, and if
* $encoding is not specified, it defaults to mb_internal_encoding(). It
* then returns the initialized object. Throws an InvalidArgumentException
* if the first argument is an array or object without a __toString method.
*
* @param mixed $str Value to modify, after being cast to string
* @param string $encoding The character encoding
* @return static A Stringy object
* @throws \InvalidArgumentException if an array or object without a
* __toString method is passed as the first argument
*/
public static function create($str = '', $encoding = null)
{
return new static($str, $encoding);
}
/**
* Returns the value in $str.
*
* @return string The current value of the $str property
*/
public function __toString()
{
return $this->str;
}
/**
* Returns a new string with $string appended.
*
* @param string $string The string to append
* @return static Object with appended $string
*/
public function append($string)
{
return static::create($this->str . $string, $this->encoding);
}
/**
* Returns the character at $index, with indexes starting at 0.
*
* @param int $index Position of the character
* @return static The character at $index
*/
public function at($index)
{
return $this->substr($index, 1);
}
/**
* 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 $start Delimiter marking the start of the substring
* @param string $end Delimiter marking the end of the substring
* @param int $offset Index from which to begin the search
* @return static Object whose $str is a substring between $start and $end
*/
public function between($start, $end, $offset = 0)
{
$startIndex = $this->indexOf($start, $offset);
if ($startIndex === false) {
return static::create('', $this->encoding);
}
$substrIndex = $startIndex + \mb_strlen($start, $this->encoding);
$endIndex = $this->indexOf($end, $substrIndex);
if ($endIndex === false) {
return static::create('', $this->encoding);
}
return $this->substr($substrIndex, $endIndex - $substrIndex);
}
/**
* Returns a camelCase version of the string. Trims surrounding spaces,
* capitalizes letters following digits, spaces, dashes and underscores,
* and removes spaces, dashes, as well as underscores.
*
* @return static Object with $str in camelCase
*/
public function camelize()
{
$encoding = $this->encoding;
$stringy = $this->trim()->lowerCaseFirst();
$stringy->str = preg_replace('/^[-_]+/', '', $stringy->str);
$stringy->str = preg_replace_callback(
'/[-_\s]+(.)?/u',
function ($match) use ($encoding) {
if (isset($match[1])) {
return \mb_strtoupper($match[1], $encoding);
}
return '';
},
$stringy->str
);
$stringy->str = preg_replace_callback(
'/[\d]+(.)?/u',
function ($match) use ($encoding) {
return \mb_strtoupper($match[0], $encoding);
},
$stringy->str
);
return $stringy;
}
/**
* Returns an array consisting of the characters in the string.
*
* @return array An array of string chars
*/
public function chars()
{
$chars = [];
for ($i = 0, $l = $this->length(); $i < $l; $i++) {
$chars[] = $this->at($i)->str;
}
return $chars;
}
/**
* 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.
*
* @return static Object with a trimmed $str and condensed whitespace
*/
public function collapseWhitespace()
{
return $this->regexReplace('[[:space:]]+', ' ')->trim();
}
/**
* 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 $needle Substring to look for
* @param bool $caseSensitive Whether or not to enforce case-sensitivity
* @return bool Whether or not $str contains $needle
*/
public function contains($needle, $caseSensitive = true)
{
$encoding = $this->encoding;
if ($caseSensitive) {
return (\mb_strpos($this->str, $needle, 0, $encoding) !== false);
}
return (\mb_stripos($this->str, $needle, 0, $encoding) !== 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[] $needles Substrings to look for
* @param bool $caseSensitive Whether or not to enforce case-sensitivity
* @return bool Whether or not $str contains $needle
*/
public function containsAll($needles, $caseSensitive = true)
{
if (empty($needles)) {
return false;
}
foreach ($needles as $needle) {
if (!$this->contains($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[] $needles Substrings to look for
* @param bool $caseSensitive Whether or not to enforce case-sensitivity
* @return bool Whether or not $str contains $needle
*/
public function containsAny($needles, $caseSensitive = true)
{
if (empty($needles)) {
return false;
}
foreach ($needles as $needle) {
if ($this->contains($needle, $caseSensitive)) {
return true;
}
}
return false;
}
/**
* Returns the length of the string, implementing the countable interface.
*
* @return int The number of characters in the string, given the encoding
*/
public function count()
{
return $this->length();
}
/**
* 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 $substring The substring to search for
* @param bool $caseSensitive Whether or not to enforce case-sensitivity
* @return int The number of $substring occurrences
*/
public function countSubstr($substring, $caseSensitive = true)
{
if ($caseSensitive) {
return \mb_substr_count($this->str, $substring, $this->encoding);
}
$str = \mb_strtoupper($this->str, $this->encoding);
$substring = \mb_strtoupper($substring, $this->encoding);
return \mb_substr_count($str, $substring, $this->encoding);
}
/**
* 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.
*
* @return static Object with a dasherized $str
*/
public function dasherize()
{
return $this->delimit('-');
}
/**
* 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 $delimiter Sequence used to separate parts of the string
* @return static Object with a delimited $str
*/
public function delimit($delimiter)
{
$regexEncoding = $this->regexEncoding();
$this->regexEncoding($this->encoding);
$str = $this->eregReplace('\B([A-Z])', '-\1', $this->trim());
$str = \mb_strtolower($str, $this->encoding);
$str = $this->eregReplace('[-_\s]+', $delimiter, $str);
$this->regexEncoding($regexEncoding);
return static::create($str, $this->encoding);
}
/**
* Returns true if the string ends with $substring, false otherwise. By
* default, the comparison is case-sensitive, but can be made insensitive
* by setting $caseSensitive to false.
*
* @param string $substring The substring to look for
* @param bool $caseSensitive Whether or not to enforce case-sensitivity
* @return bool Whether or not $str ends with $substring
*/
public function endsWith($substring, $caseSensitive = true)
{
$substringLength = \mb_strlen($substring, $this->encoding);
$strLength = $this->length();
$endOfStr = \mb_substr($this->str, $strLength - $substringLength,
$substringLength, $this->encoding);
if (!$caseSensitive) {
$substring = \mb_strtolower($substring, $this->encoding);
$endOfStr = \mb_strtolower($endOfStr, $this->encoding);
}
return (string) $substring === $endOfStr;
}
/**
* 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[] $substrings Substrings to look for
* @param bool $caseSensitive Whether or not to enforce
* case-sensitivity
* @return bool Whether or not $str ends with $substring
*/
public function endsWithAny($substrings, $caseSensitive = true)
{
if (empty($substrings)) {
return false;
}
foreach ($substrings as $substring) {
if ($this->endsWith($substring, $caseSensitive)) {
return true;
}
}
return false;
}
/**
* Ensures that the string begins with $substring. If it doesn't, it's
* prepended.
*
* @param string $substring The substring to add if not present
* @return static Object with its $str prefixed by the $substring
*/
public function ensureLeft($substring)
{
$stringy = static::create($this->str, $this->encoding);
if (!$stringy->startsWith($substring)) {
$stringy->str = $substring . $stringy->str;
}
return $stringy;
}
/**
* Ensures that the string ends with $substring. If it doesn't, it's
* appended.
*
* @param string $substring The substring to add if not present
* @return static Object with its $str suffixed by the $substring
*/
public function ensureRight($substring)
{
$stringy = static::create($this->str, $this->encoding);
if (!$stringy->endsWith($substring)) {
$stringy->str .= $substring;
}
return $stringy;
}
/**
* Returns the first $n characters of the string.
*
* @param int $n Number of characters to retrieve from the start
* @return static Object with its $str being the first $n chars
*/
public function first($n)
{
$stringy = static::create($this->str, $this->encoding);
if ($n < 0) {
$stringy->str = '';
return $stringy;
}
return $stringy->substr(0, $n);
}
/**
* Returns the encoding used by the Stringy object.
*
* @return string The current value of the $encoding property
*/
public function getEncoding()
{
return $this->encoding;
}
/**
* Returns a new ArrayIterator, thus implementing the IteratorAggregate
* interface. The ArrayIterator's constructor is passed an array of chars
* in the multibyte string. This enables the use of foreach with instances
* of Stringy\Stringy.
*
* @return \ArrayIterator An iterator for the characters in the string
*/
public function getIterator()
{
return new ArrayIterator($this->chars());
}
/**
* Returns true if the string contains a lower case char, false
* otherwise.
*
* @return bool Whether or not the string contains a lower case character.
*/
public function hasLowerCase()
{
return $this->matchesPattern('.*[[:lower:]]');
}
/**
* Returns true if the string contains an upper case char, false
* otherwise.
*
* @return bool Whether or not the string contains an upper case character.
*/
public function hasUpperCase()
{
return $this->matchesPattern('.*[[:upper:]]');
}
/**
* Convert all HTML entities to their applicable characters. An alias of
* html_entity_decode. For a list of flags, refer to
* http://php.net/manual/en/function.html-entity-decode.php
*
* @param int|null $flags Optional flags
* @return static Object with the resulting $str after being html decoded.
*/
public function htmlDecode($flags = ENT_COMPAT)
{
$str = html_entity_decode($this->str, $flags, $this->encoding);
return static::create($str, $this->encoding);
}
/**
* Convert all applicable characters to HTML entities. An alias of
* htmlentities. Refer to http://php.net/manual/en/function.htmlentities.php
* for a list of flags.
*
* @param int|null $flags Optional flags
* @return static Object with the resulting $str after being html encoded.
*/
public function htmlEncode($flags = ENT_COMPAT)
{
$str = htmlentities($this->str, $flags, $this->encoding);
return static::create($str, $this->encoding);
}
/**
* Capitalizes the first word of the string, replaces underscores with
* spaces, and strips '_id'.
*
* @return static Object with a humanized $str
*/
public function humanize()
{
$str = str_replace(['_id', '_'], ['', ' '], $this->str);
return static::create($str, $this->encoding)->trim()->upperCaseFirst();
}
/**
* 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 $needle Substring to look for
* @param int $offset Offset from which to search
* @return int|bool The occurrence's index if found, otherwise false
*/
public function indexOf($needle, $offset = 0)
{
return \mb_strpos($this->str, (string) $needle,
(int) $offset, $this->encoding);
}
/**
* 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 $needle Substring to look for
* @param int $offset Offset from which to search
* @return int|bool The last occurrence's index if found, otherwise false
*/
public function indexOfLast($needle, $offset = 0)
{
return \mb_strrpos($this->str, (string) $needle,
(int) $offset, $this->encoding);
}
/**
* Inserts $substring into the string at the $index provided.
*
* @param string $substring String to be inserted
* @param int $index The index at which to insert the substring
* @return static Object with the resulting $str after the insertion
*/
public function insert($substring, $index)
{
$stringy = static::create($this->str, $this->encoding);
if ($index > $stringy->length()) {
return $stringy;
}
$start = \mb_substr($stringy->str, 0, $index, $stringy->encoding);
$end = \mb_substr($stringy->str, $index, $stringy->length(),
$stringy->encoding);
$stringy->str = $start . $substring . $end;
return $stringy;
}
/**
* Returns true if the string contains only alphabetic chars, false
* otherwise.
*
* @return bool Whether or not $str contains only alphabetic chars
*/
public function isAlpha()
{
return $this->matchesPattern('^[[:alpha:]]*$');
}
/**
* Returns true if the string contains only alphabetic and numeric chars,
* false otherwise.
*
* @return bool Whether or not $str contains only alphanumeric chars
*/
public function isAlphanumeric()
{
return $this->matchesPattern('^[[:alnum:]]*$');
}
/**
* Returns true if the string contains only whitespace chars, false
* otherwise.
*
* @return bool Whether or not $str contains only whitespace characters
*/
public function isBlank()
{
return $this->matchesPattern('^[[:space:]]*$');
}
/**
* Returns true if the string contains only hexadecimal chars, false
* otherwise.
*
* @return bool Whether or not $str contains only hexadecimal chars
*/
public function isHexadecimal()
{
return $this->matchesPattern('^[[:xdigit:]]*$');
}
/**
* Returns true if the string is JSON, false otherwise. Unlike json_decode
* in PHP 5.x, this method is consistent with PHP 7 and other JSON parsers,
* in that an empty string is not considered valid JSON.
*
* @return bool Whether or not $str is JSON
*/
public function isJson()
{
if (!$this->length()) {
return false;
}
json_decode($this->str);
return (json_last_error() === JSON_ERROR_NONE);
}
/**
* Returns true if the string contains only lower case chars, false
* otherwise.
*
* @return bool Whether or not $str contains only lower case characters
*/
public function isLowerCase()
{
return $this->matchesPattern('^[[:lower:]]*$');
}
/**
* Returns true if the string is serialized, false otherwise.
*
* @return bool Whether or not $str is serialized
*/
public function isSerialized()
{
return $this->str === 'b:0;' || @unserialize($this->str) !== false;
}
/**
* Returns true if the string is base64 encoded, false otherwise.
*
* @return bool Whether or not $str is base64 encoded
*/
public function isBase64()
{
return (base64_encode(base64_decode($this->str, true)) === $this->str);
}
/**
* Returns true if the string contains only lower case chars, false
* otherwise.
*
* @return bool Whether or not $str contains only lower case characters
*/
public function isUpperCase()
{
return $this->matchesPattern('^[[:upper:]]*$');
}
/**
* Returns the last $n characters of the string.
*
* @param int $n Number of characters to retrieve from the end
* @return static Object with its $str being the last $n chars
*/
public function last($n)
{
$stringy = static::create($this->str, $this->encoding);
if ($n <= 0) {
$stringy->str = '';
return $stringy;
}
return $stringy->substr(-$n);
}
/**
* Returns the length of the string. An alias for PHP's mb_strlen() function.
*
* @return int The number of characters in $str given the encoding
*/
public function length()
{
return \mb_strlen($this->str, $this->encoding);
}
/**
* Splits on newlines and carriage returns, returning an array of Stringy
* objects corresponding to the lines in the string.
*
* @return static[] An array of Stringy objects
*/
public function lines()
{
$array = $this->split('[\r\n]{1,2}', $this->str);
for ($i = 0; $i < count($array); $i++) {
$array[$i] = static::create($array[$i], $this->encoding);
}
return $array;
}
/**
* Returns the longest common prefix between the string and $otherStr.
*
* @param string $otherStr Second string for comparison
* @return static Object with its $str being the longest common prefix
*/
public function longestCommonPrefix($otherStr)
{
$encoding = $this->encoding;
$maxLength = min($this->length(), \mb_strlen($otherStr, $encoding));
$longestCommonPrefix = '';
for ($i = 0; $i < $maxLength; $i++) {
$char = \mb_substr($this->str, $i, 1, $encoding);
if ($char == \mb_substr($otherStr, $i, 1, $encoding)) {
$longestCommonPrefix .= $char;
} else {
break;
}
}
return static::create($longestCommonPrefix, $encoding);
}
/**
* Returns the longest common suffix between the string and $otherStr.
*
* @param string $otherStr Second string for comparison
* @return static Object with its $str being the longest common suffix
*/
public function longestCommonSuffix($otherStr)
{
$encoding = $this->encoding;
$maxLength = min($this->length(), \mb_strlen($otherStr, $encoding));
$longestCommonSuffix = '';
for ($i = 1; $i <= $maxLength; $i++) {
$char = \mb_substr($this->str, -$i, 1, $encoding);
if ($char == \mb_substr($otherStr, -$i, 1, $encoding)) {
$longestCommonSuffix = $char . $longestCommonSuffix;
} else {
break;
}
}
return static::create($longestCommonSuffix, $encoding);
}
/**
* Returns the longest common substring between the string and $otherStr.
* In the case of ties, it returns that which occurs first.
*
* @param string $otherStr Second string for comparison
* @return static Object with its $str being the longest common substring
*/
public function longestCommonSubstring($otherStr)
{
// Uses dynamic programming to solve
// http://en.wikipedia.org/wiki/Longest_common_substring_problem
$encoding = $this->encoding;
$stringy = static::create($this->str, $encoding);
$strLength = $stringy->length();
$otherLength = \mb_strlen($otherStr, $encoding);
// Return if either string is empty
if ($strLength == 0 || $otherLength == 0) {
$stringy->str = '';
return $stringy;
}
$len = 0;
$end = 0;
$table = array_fill(0, $strLength + 1,
array_fill(0, $otherLength + 1, 0));
for ($i = 1; $i <= $strLength; $i++) {
for ($j = 1; $j <= $otherLength; $j++) {
$strChar = \mb_substr($stringy->str, $i - 1, 1, $encoding);
$otherChar = \mb_substr($otherStr, $j - 1, 1, $encoding);
if ($strChar == $otherChar) {
$table[$i][$j] = $table[$i - 1][$j - 1] + 1;
if ($table[$i][$j] > $len) {
$len = $table[$i][$j];
$end = $i;
}
} else {
$table[$i][$j] = 0;
}
}
}
$stringy->str = \mb_substr($stringy->str, $end - $len, $len, $encoding);
return $stringy;
}
/**
* Converts the first character of the string to lower case.
*
* @return static Object with the first character of $str being lower case
*/
public function lowerCaseFirst()
{
$first = \mb_substr($this->str, 0, 1, $this->encoding);
$rest = \mb_substr($this->str, 1, $this->length() - 1,
$this->encoding);
$str = \mb_strtolower($first, $this->encoding) . $rest;
return static::create($str, $this->encoding);
}
/**
* Returns whether or not a character exists at an index. Offsets may be
* negative to count from the last character in the string. Implements
* part of the ArrayAccess interface.
*
* @param mixed $offset The index to check
* @return boolean Whether or not the index exists
*/
public function offsetExists($offset)
{
$length = $this->length();
$offset = (int) $offset;
if ($offset >= 0) {
return ($length > $offset);
}
return ($length >= abs($offset));
}
/**
* Returns the character at the given index. Offsets may be negative to
* count from the last character in the string. Implements part of the
* ArrayAccess interface, and throws an OutOfBoundsException if the index
* does not exist.
*
* @param mixed $offset The index from which to retrieve the char
* @return mixed The character at the specified index
* @throws \OutOfBoundsException If the positive or negative offset does
* not exist
*/
public function offsetGet($offset)
{
$offset = (int) $offset;
$length = $this->length();
if (($offset >= 0 && $length <= $offset) || $length < abs($offset)) {
throw new OutOfBoundsException('No character exists at the index');
}
return \mb_substr($this->str, $offset, 1, $this->encoding);
}
/**
* Implements part of the ArrayAccess interface, but throws an exception
* when called. This maintains the immutability of Stringy objects.
*
* @param mixed $offset The index of the character
* @param mixed $value Value to set
* @throws \Exception When called
*/
public function offsetSet($offset, $value)
{
// Stringy is immutable, cannot directly set char
throw new Exception('Stringy object is immutable, cannot modify char');
}
/**
* Implements part of the ArrayAccess interface, but throws an exception
* when called. This maintains the immutability of Stringy objects.
*
* @param mixed $offset The index of the character
* @throws \Exception When called
*/
public function offsetUnset($offset)
{
// Don't allow directly modifying the string
throw new Exception('Stringy object is immutable, cannot unset char');
}
/**
* Pads the string to a given length with $padStr. If length is less than
* or equal to the length of the string, no padding takes places. The
* default string used for padding is a space, and the default type (one of
* 'left', 'right', 'both') is 'right'. Throws an InvalidArgumentException
* if $padType isn't one of those 3 values.
*
* @param int $length Desired string length after padding
* @param string $padStr String used to pad, defaults to space
* @param string $padType One of 'left', 'right', 'both'
* @return static Object with a padded $str
* @throws /InvalidArgumentException If $padType isn't one of 'right',
* 'left' or 'both'
*/
public function pad($length, $padStr = ' ', $padType = 'right')
{
if (!in_array($padType, ['left', 'right', 'both'])) {
throw new InvalidArgumentException('Pad expects $padType ' .
"to be one of 'left', 'right' or 'both'");
}
switch ($padType) {
case 'left':
return $this->padLeft($length, $padStr);
case 'right':
return $this->padRight($length, $padStr);
default:
return $this->padBoth($length, $padStr);
}
}
/**
* Returns a new string of a given length such that both sides of the
* string are padded. Alias for pad() with a $padType of 'both'.
*
* @param int $length Desired string length after padding
* @param string $padStr String used to pad, defaults to space
* @return static String with padding applied
*/
public function padBoth($length, $padStr = ' ')
{
$padding = $length - $this->length();
return $this->applyPadding(floor($padding / 2), ceil($padding / 2),
$padStr);
}
/**
* Returns a new string of a given length such that the beginning of the
* string is padded. Alias for pad() with a $padType of 'left'.
*
* @param int $length Desired string length after padding
* @param string $padStr String used to pad, defaults to space
* @return static String with left padding
*/
public function padLeft($length, $padStr = ' ')
{
return $this->applyPadding($length - $this->length(), 0, $padStr);
}
/**
* Returns a new string of a given length such that the end of the string
* is padded. Alias for pad() with a $padType of 'right'.
*
* @param int $length Desired string length after padding
* @param string $padStr String used to pad, defaults to space
* @return static String with right padding
*/
public function padRight($length, $padStr = ' ')
{
return $this->applyPadding(0, $length - $this->length(), $padStr);
}
/**
* Returns a new string starting with $string.
*
* @param string $string The string to append
* @return static Object with appended $string
*/
public function prepend($string)
{
return static::create($string . $this->str, $this->encoding);
}
/**
* Replaces all occurrences of $pattern in $str by $replacement. An alias
* for mb_ereg_replace(). Note that the 'i' option with multibyte patterns
* in mb_ereg_replace() requires PHP 5.6+ for correct results. This is due
* to a lack of support in the bundled version of Oniguruma in PHP < 5.6,