• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

voku / Stringy / 24755654962

22 Apr 2026 01:38AM UTC coverage: 97.987%. Remained the same
24755654962

Pull #51

github

web-flow
Merge c3d584394 into 0f66f2b48
Pull Request #51: Fix camelize and upperCamelize for all-caps inputs

1022 of 1043 relevant lines covered (97.99%)

69.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.86
/src/Stringy.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Stringy;
6

7
use Defuse\Crypto\Crypto;
8
use voku\helper\AntiXSS;
9
use voku\helper\ASCII;
10
use voku\helper\EmailCheck;
11
use voku\helper\URLify;
12
use voku\helper\UTF8;
13

14
/**
15
 * ## 🇷🇺 Русским гражданам
16
 * В Украине сейчас идет война. Силами РФ наносятся удары по гражданской инфраструктуре в [Харькове][1], [Киеве][2], [Чернигове][3], [Сумах][4], [Ирпене][5] и десятках других городов. Гибнут люди - и гражданское население, и военные, в том числе российские призывники, которых бросили воевать. Чтобы лишить собственный народ доступа к информации, правительство РФ запретило называть войну войной, закрыло независимые СМИ и принимает сейчас ряд диктаторских законов. Эти законы призваны заткнуть рот всем, кто против войны. За обычный призыв к миру сейчас можно получить несколько лет тюрьмы.
17
 * Не молчите! Молчание - знак вашего согласия с политикой российского правительства.
18
 *  **Вы можете сделать выбор НЕ МОЛЧАТЬ.**
19
 * ---
20
 * ## 🇺🇸 To people of Russia
21
 * There is a war in Ukraine right now. The forces of the Russian Federation are attacking civilian infrastructure in [Kharkiv][1], [Kyiv][2], [Chernihiv][3], [Sumy][4], [Irpin][5] and dozens of other cities. People are dying – both civilians and military servicemen, including Russian conscripts who were thrown into the fighting. In order to deprive its own people of access to information, the government of the Russian Federation has forbidden calling a war a war, shut down independent media and is passing a number of dictatorial laws. These laws are meant to silence all those who are against war. You can be jailed for multiple years for simply calling for peace.
22
 * Do not be silent! Silence is a sign that you accept the Russian government's policy.
23
 * **You can choose NOT TO BE SILENT.**
24
 * ---
25
 * - [1] https://cloudfront-us-east-2.images.arcpublishing.com/reuters/P7K2MSZDGFMIJPDD7CI2GIROJI.jpg "Kharkiv under attack"
26
 * - [2] https://gdb.voanews.com/01bd0000-0aff-0242-fad0-08d9fc92c5b3_cx0_cy5_cw0_w1023_r1_s.jpg "Kyiv under attack"
27
 * - [3] https://ichef.bbci.co.uk/news/976/cpsprodpb/163DD/production/_123510119_hi074310744.jpg "Chernihiv under attack"
28
 * - [4] https://www.youtube.com/watch?v=8K-bkqKKf2A "Sumy under attack"
29
 * - [5] https://cloudfront-us-east-2.images.arcpublishing.com/reuters/K4MTMLEHTRKGFK3GSKAT4GR3NE.jpg "Irpin under attack"
30
 *
31
 * @template-implements \IteratorAggregate<string>
32
 * @template-implements \ArrayAccess<array-key,string>
33
 */
34
class Stringy implements \ArrayAccess, \Countable, \IteratorAggregate, \JsonSerializable
35
{
36
    /**
37
     * An instance's string.
38
     *
39
     * @var string
40
     */
41
    protected $str;
42

43
    /**
44
     * The string's encoding, which should be one of the mbstring module's
45
     * supported encodings.
46
     *
47
     * @var string
48
     */
49
    protected $encoding;
50

51
    /**
52
     * @var UTF8
53
     */
54
    private $utf8;
55

56
    /**
57
     * @var ASCII
58
     */
59
    private $ascii;
60

61
    /**
62
     * Initializes a Stringy object and assigns both str and encoding properties
63
     * the supplied values. $str is cast to a string prior to assignment, and if
64
     * $encoding is not specified, it defaults to mb_internal_encoding(). Throws
65
     * an InvalidArgumentException if the first argument is an array or object
66
     * without a __toString method.
67
     *
68
     * @param object|scalar $str      [optional] <p>Value to modify, after being cast to string. Default: ''</p>
69
     * @param string        $encoding [optional] <p>The character encoding. Fallback: 'UTF-8'</p>
70
     *
71
     * @throws \InvalidArgumentException
72
     *                                   <p>if an array or object without a
73
     *                                   __toString method is passed as the first argument</p>
74
     *
75
     * @psalm-mutation-free
76
     */
77
    public function __construct($str = '', ?string $encoding = null)
78
    {
79
        /* @phpstan-ignore-next-line | always false in theory */
80
        if (\is_array($str)) {
3,699✔
81
            throw new \InvalidArgumentException(
3✔
82
                'Passed value cannot be an array'
3✔
83
            );
3✔
84
        }
85

86
        if (
87
            \is_object($str)
3,696✔
88
            &&
89
            !\method_exists($str, '__toString')
3,696✔
90
        ) {
91
            throw new \InvalidArgumentException(
4✔
92
                'Passed object must have a __toString method'
4✔
93
            );
4✔
94
        }
95

96
        $this->str = (string) $str;
3,693✔
97

98
        static $ASCII = null;
3,693✔
99
        if ($ASCII === null) {
3,693✔
100
            $ASCII = new ASCII();
×
101
        }
102
        $this->ascii = $ASCII;
3,693✔
103

104
        static $UTF8 = null;
3,693✔
105
        if ($UTF8 === null) {
3,693✔
106
            $UTF8 = new UTF8();
×
107
        }
108
        $this->utf8 = $UTF8;
3,693✔
109

110
        if ($encoding !== 'UTF-8') {
3,693✔
111
            $this->encoding = $this->utf8::normalize_encoding($encoding, 'UTF-8');
2,510✔
112
        } else {
113
            $this->encoding = $encoding;
2,753✔
114
        }
115
    }
116

117
    /**
118
     * Returns the value in $str.
119
     *
120
     * EXAMPLE: <code>
121
     * </code>
122
     *
123
     * @psalm-mutation-free
124
     *
125
     * @return string
126
     *                <p>The current value of the $str property.</p>
127
     */
128
    public function __toString()
129
    {
130
        return (string) $this->str;
1,161✔
131
    }
132

133
    /**
134
     * Return part of the string occurring after a specific string.
135
     *
136
     * EXAMPLE: <code>
137
     * s('宮本 茂')->after('本'); // ' 茂'
138
     * </code>
139
     *
140
     * @param string $string <p>The delimiting string.</p>
141
     *
142
     * @psalm-mutation-free
143
     *
144
     * @return static
145
     */
146
    public function after(string $string): self
147
    {
148
        $strArray = UTF8::str_split_pattern(
4✔
149
            $this->str,
4✔
150
            $string
4✔
151
        );
4✔
152

153
        unset($strArray[0]);
4✔
154

155
        return new static(
4✔
156
            \implode(' ', $strArray),
4✔
157
            $this->encoding
4✔
158
        );
4✔
159
    }
160

161
    /**
162
     * Gets the substring after the first occurrence of a separator.
163
     * If no match is found returns new empty Stringy object.
164
     *
165
     * EXAMPLE: <code>
166
     * s('</b></b>')->afterFirst('b'); // '></b>'
167
     * </code>
168
     *
169
     * @param string $separator
170
     *
171
     * @psalm-mutation-free
172
     *
173
     * @return static
174
     */
175
    public function afterFirst(string $separator): self
176
    {
177
        return static::create(
3✔
178
            $this->utf8::str_substr_after_first_separator(
3✔
179
                $this->str,
3✔
180
                $separator,
3✔
181
                $this->encoding
3✔
182
            )
3✔
183
        );
3✔
184
    }
185

186
    /**
187
     * Gets the substring after the first occurrence of a separator.
188
     * If no match is found returns new empty Stringy object.
189
     *
190
     * EXAMPLE: <code>
191
     * s('</B></B>')->afterFirstIgnoreCase('b'); // '></B>'
192
     * </code>
193
     *
194
     * @param string $separator
195
     *
196
     * @psalm-mutation-free
197
     *
198
     * @return static
199
     */
200
    public function afterFirstIgnoreCase(string $separator): self
201
    {
202
        return static::create(
2✔
203
            $this->utf8::str_isubstr_after_first_separator(
2✔
204
                $this->str,
2✔
205
                $separator,
2✔
206
                $this->encoding
2✔
207
            )
2✔
208
        );
2✔
209
    }
210

211
    /**
212
     * Gets the substring after the last occurrence of a separator.
213
     * If no match is found returns new empty Stringy object.
214
     *
215
     * EXAMPLE: <code>
216
     * s('</b></b>')->afterLast('b'); // '>'
217
     * </code>
218
     *
219
     * @param string $separator
220
     *
221
     * @psalm-mutation-free
222
     *
223
     * @return static
224
     */
225
    public function afterLast(string $separator): self
226
    {
227
        return static::create(
2✔
228
            $this->utf8::str_substr_after_last_separator(
2✔
229
                $this->str,
2✔
230
                $separator,
2✔
231
                $this->encoding
2✔
232
            )
2✔
233
        );
2✔
234
    }
235

236
    /**
237
     * Gets the substring after the last occurrence of a separator.
238
     * If no match is found returns new empty Stringy object.
239
     *
240
     * EXAMPLE: <code>
241
     * s('</B></B>')->afterLastIgnoreCase('b'); // '>'
242
     * </code>
243
     *
244
     * @param string $separator
245
     *
246
     * @psalm-mutation-free
247
     *
248
     * @return static
249
     */
250
    public function afterLastIgnoreCase(string $separator): self
251
    {
252
        return static::create(
2✔
253
            $this->utf8::str_isubstr_after_last_separator(
2✔
254
                $this->str,
2✔
255
                $separator,
2✔
256
                $this->encoding
2✔
257
            )
2✔
258
        );
2✔
259
    }
260

261
    /**
262
     * Returns a new string with $suffix appended.
263
     *
264
     * EXAMPLE: <code>
265
     * s('fòô')->append('bàř'); // 'fòôbàř'
266
     * </code>
267
     *
268
     * @param string ...$suffix <p>The string to append.</p>
269
     *
270
     * @psalm-mutation-free
271
     *
272
     * @return static
273
     *                <p>Object with appended $suffix.</p>
274
     */
275
    public function append(string ...$suffix): self
276
    {
277
        if (\count($suffix) <= 1) {
21✔
278
            $suffix = $suffix[0];
19✔
279
        } else {
280
            $suffix = \implode('', $suffix);
2✔
281
        }
282

283
        return static::create($this->str . $suffix, $this->encoding);
21✔
284
    }
285

286
    /**
287
     * Append an password (limited to chars that are good readable).
288
     *
289
     * EXAMPLE: <code>
290
     * s('')->appendPassword(8); // e.g.: '89bcdfgh'
291
     * </code>
292
     *
293
     * @param int $length <p>Length of the random string.</p>
294
     *
295
     * @return static
296
     *                <p>Object with appended password.</p>
297
     */
298
    public function appendPassword(int $length): self
299
    {
300
        return $this->appendRandomString(
2✔
301
            $length,
2✔
302
            '2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ!?_#'
2✔
303
        );
2✔
304
    }
305

306
    /**
307
     * Append an random string.
308
     *
309
     * EXAMPLE: <code>
310
     * s('')->appendUniqueIdentifier(5, 'ABCDEFGHI'); // e.g.: 'CDEHI'
311
     * </code>
312
     *
313
     * @param int    $length        <p>Length of the random string.</p>
314
     * @param string $possibleChars [optional] <p>Characters string for the random selection.</p>
315
     *
316
     * @return static
317
     *                <p>Object with appended random string.</p>
318
     */
319
    public function appendRandomString(int $length, string $possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'): self
320
    {
321
        if ($length <= 0 || $possibleChars === '') {
10✔
322
            return $this->append('');
6✔
323
        }
324

325
        $str = $this->utf8::get_random_string($length, $possibleChars);
6✔
326

327
        return $this->append($str);
6✔
328
    }
329

330
    /**
331
     * Returns a new string with $suffix appended.
332
     *
333
     * EXAMPLE: <code>
334
     * </code>
335
     *
336
     * @param CollectionStringy|static ...$suffix <p>The Stringy objects to append.</p>
337
     *
338
     * @phpstan-param CollectionStringy<int,static>|static ...$suffix
339
     *
340
     * @psalm-mutation-free
341
     *
342
     * @return static
343
     *                <p>Object with appended $suffix.</p>
344
     */
345
    public function appendStringy(...$suffix): self
346
    {
347
        $suffixStr = '';
7✔
348
        foreach ($suffix as $suffixTmp) {
7✔
349
            if ($suffixTmp instanceof CollectionStringy) {
7✔
350
                $suffixStr .= $suffixTmp->implode('');
1✔
351
            } else {
352
                $suffixStr .= $suffixTmp->toString();
7✔
353
            }
354
        }
355

356
        return static::create($this->str . $suffixStr, $this->encoding);
7✔
357
    }
358

359
    /**
360
     * Append an unique identifier.
361
     *
362
     * EXAMPLE: <code>
363
     * s('')->appendUniqueIdentifier(); // e.g.: '1f3870be274f6c49b3e31a0c6728957f'
364
     * </code>
365
     *
366
     * @param int|string $entropyExtra [optional] <p>Extra entropy via a string or int value.</p>
367
     * @param bool       $md5          [optional] <p>Return the unique identifier as md5-hash? Default: true</p>
368
     *
369
     * @return static
370
     *                <p>Object with appended unique identifier as md5-hash.</p>
371
     */
372
    public function appendUniqueIdentifier($entropyExtra = '', bool $md5 = true): self
373
    {
374
        return $this->append(
2✔
375
            $this->utf8::get_unique_string($entropyExtra, $md5)
2✔
376
        );
2✔
377
    }
378

379
    /**
380
     * Returns the character at $index, with indexes starting at 0.
381
     *
382
     * EXAMPLE: <code>
383
     * s('fòôbàř')->at(3); // 'b'
384
     * </code>
385
     *
386
     * @param int $index <p>Position of the character.</p>
387
     *
388
     * @psalm-mutation-free
389
     *
390
     * @return static
391
     *                <p>The character at $index.</p>
392
     */
393
    public function at(int $index): self
394
    {
395
        if ($this->encoding === 'UTF-8') {
32✔
396
            return static::create((string) \mb_substr($this->str, $index, 1), $this->encoding);
32✔
397
        }
398

399
        return static::create($this->utf8::substr($this->str, $index, 1, $this->encoding), $this->encoding);
×
400
    }
401

402
    /**
403
     * Decode the base64 encoded string.
404
     *
405
     * EXAMPLE: <code>
406
     * </code>
407
     *
408
     * @psalm-mutation-free
409
     *
410
     * @return self
411
     */
412
    public function base64Decode(): self
413
    {
414
        return static::create(
2✔
415
            \base64_decode($this->str, true),
2✔
416
            $this->encoding
2✔
417
        );
2✔
418
    }
419

420
    /**
421
     * Encode the string to base64.
422
     *
423
     * EXAMPLE: <code>
424
     * </code>
425
     *
426
     * @psalm-mutation-free
427
     *
428
     * @return self
429
     */
430
    public function base64Encode(): self
431
    {
432
        return static::create(
2✔
433
            \base64_encode($this->str),
2✔
434
            $this->encoding
2✔
435
        );
2✔
436
    }
437

438
    /**
439
     * Creates a hash from the string using the CRYPT_BLOWFISH algorithm.
440
     *
441
     * WARNING: Using this algorithm, will result in the ```$this->str```
442
     *          being truncated to a maximum length of 72 characters.
443
     *
444
     * EXAMPLE: <code>
445
     * </code>
446
     *
447
     * @param array<array-key, int|string> $options [optional] <p>An array of bcrypt hashing options.</p>
448
     *
449
     * @psalm-mutation-free
450
     *
451
     * @return static
452
     */
453
    public function bcrypt(array $options = []): self
454
    {
455
        return new static(
3✔
456
            \password_hash(
3✔
457
                $this->str,
3✔
458
                \PASSWORD_BCRYPT,
3✔
459
                $options
3✔
460
            ),
3✔
461
            $this->encoding
3✔
462
        );
3✔
463
    }
464

465
    /**
466
     * Return part of the string occurring before a specific string.
467
     *
468
     * EXAMPLE: <code>
469
     * </code>
470
     *
471
     * @param string $string <p>The delimiting string.</p>
472
     *
473
     * @psalm-mutation-free
474
     *
475
     * @return static
476
     */
477
    public function before(string $string): self
478
    {
479
        $strArray = UTF8::str_split_pattern(
4✔
480
            $this->str,
4✔
481
            $string,
4✔
482
            1
4✔
483
        );
4✔
484

485
        return new static(
4✔
486
            $strArray[0] ?? '',
4✔
487
            $this->encoding
4✔
488
        );
4✔
489
    }
490

491
    /**
492
     * Gets the substring before the first occurrence of a separator.
493
     * If no match is found returns new empty Stringy object.
494
     *
495
     * EXAMPLE: <code>
496
     * s('</b></b>')->beforeFirst('b'); // '</'
497
     * </code>
498
     *
499
     * @param string $separator
500
     *
501
     * @psalm-mutation-free
502
     *
503
     * @return static
504
     */
505
    public function beforeFirst(string $separator): self
506
    {
507
        return static::create(
2✔
508
            $this->utf8::str_substr_before_first_separator(
2✔
509
                $this->str,
2✔
510
                $separator,
2✔
511
                $this->encoding
2✔
512
            )
2✔
513
        );
2✔
514
    }
515

516
    /**
517
     * Gets the substring before the first occurrence of a separator.
518
     * If no match is found returns new empty Stringy object.
519
     *
520
     * EXAMPLE: <code>
521
     * s('</B></B>')->beforeFirstIgnoreCase('b'); // '</'
522
     * </code>
523
     *
524
     * @param string $separator
525
     *
526
     * @psalm-mutation-free
527
     *
528
     * @return static
529
     */
530
    public function beforeFirstIgnoreCase(string $separator): self
531
    {
532
        return static::create(
2✔
533
            $this->utf8::str_isubstr_before_first_separator(
2✔
534
                $this->str,
2✔
535
                $separator,
2✔
536
                $this->encoding
2✔
537
            )
2✔
538
        );
2✔
539
    }
540

541
    /**
542
     * Gets the substring before the last occurrence of a separator.
543
     * If no match is found returns new empty Stringy object.
544
     *
545
     * EXAMPLE: <code>
546
     * s('</b></b>')->beforeLast('b'); // '</b></'
547
     * </code>
548
     *
549
     * @param string $separator
550
     *
551
     * @psalm-mutation-free
552
     *
553
     * @return static
554
     */
555
    public function beforeLast(string $separator): self
556
    {
557
        return static::create(
2✔
558
            $this->utf8::str_substr_before_last_separator(
2✔
559
                $this->str,
2✔
560
                $separator,
2✔
561
                $this->encoding
2✔
562
            )
2✔
563
        );
2✔
564
    }
565

566
    /**
567
     * Gets the substring before the last occurrence of a separator.
568
     * If no match is found returns new empty Stringy object.
569
     *
570
     * EXAMPLE: <code>
571
     * s('</B></B>')->beforeLastIgnoreCase('b'); // '</B></'
572
     * </code>
573
     *
574
     * @param string $separator
575
     *
576
     * @psalm-mutation-free
577
     *
578
     * @return static
579
     */
580
    public function beforeLastIgnoreCase(string $separator): self
581
    {
582
        return static::create(
2✔
583
            $this->utf8::str_isubstr_before_last_separator(
2✔
584
                $this->str,
2✔
585
                $separator,
2✔
586
                $this->encoding
2✔
587
            )
2✔
588
        );
2✔
589
    }
590

591
    /**
592
     * Returns the substring between $start and $end, if found, or an empty
593
     * string. An optional offset may be supplied from which to begin the
594
     * search for the start string.
595
     *
596
     * EXAMPLE: <code>
597
     * s('{foo} and {bar}')->between('{', '}'); // 'foo'
598
     * </code>
599
     *
600
     * @param string $start  <p>Delimiter marking the start of the substring.</p>
601
     * @param string $end    <p>Delimiter marking the end of the substring.</p>
602
     * @param int    $offset [optional] <p>Index from which to begin the search. Default: 0</p>
603
     *
604
     * @psalm-mutation-free
605
     *
606
     * @return static
607
     *                <p>Object whose $str is a substring between $start and $end.</p>
608
     */
609
    public function between(string $start, string $end, ?int $offset = null): self
610
    {
611
        $str = $this->utf8::between(
48✔
612
            $this->str,
48✔
613
            $start,
48✔
614
            $end,
48✔
615
            (int) $offset,
48✔
616
            $this->encoding
48✔
617
        );
48✔
618

619
        return static::create($str, $this->encoding);
48✔
620
    }
621

622
    /**
623
     * Call a user function.
624
     *
625
     * EXAMPLE: <code>
626
     * S::create('foo bar lall')->callUserFunction(static function ($str) {
627
     *     return UTF8::str_limit($str, 8);
628
     * })->toString(); // "foo bar…"
629
     * </code>
630
     *
631
     * @param callable $function
632
     * @param mixed    ...$parameter
633
     *
634
     * @psalm-mutation-free
635
     *
636
     * @return static
637
     *                <p>Object having a $str changed via $function.</p>
638
     */
639
    public function callUserFunction(callable $function, ...$parameter): self
640
    {
641
        $str = $function($this->str, ...$parameter);
2✔
642

643
        return static::create(
2✔
644
            $str,
2✔
645
            $this->encoding
2✔
646
        );
2✔
647
    }
648

649
    /**
650
     * Returns a camelCase version of the string. Trims surrounding spaces,
651
     * capitalizes letters following digits, spaces, dashes and underscores,
652
     * and removes spaces, dashes, as well as underscores.
653
     *
654
     * EXAMPLE: <code>
655
     * s('Camel-Case')->camelize(); // 'camelCase'
656
     * </code>
657
     *
658
     * @psalm-mutation-free
659
     *
660
     * @return static
661
     *                <p>Object with $str in camelCase.</p>
662
     */
663
    public function camelize(): self
664
    {
665
        return static::create(
67✔
666
            $this->utf8::str_camelize($this->str, $this->encoding),
67✔
667
            $this->encoding
67✔
668
        );
67✔
669
    }
670

671
    /**
672
     * Returns the string with the first letter of each word capitalized,
673
     * except for when the word is a name which shouldn't be capitalized.
674
     *
675
     * EXAMPLE: <code>
676
     * s('jaap de hoop scheffer')->capitalizePersonName(); // 'Jaap de Hoop Scheffer'
677
     * </code>
678
     *
679
     * @psalm-mutation-free
680
     *
681
     * @return static
682
     *                <p>Object with $str capitalized.</p>
683
     */
684
    public function capitalizePersonalName(): self
685
    {
686
        return static::create(
78✔
687
            $this->utf8::str_capitalize_name($this->str),
78✔
688
            $this->encoding
78✔
689
        );
78✔
690
    }
691

692
    /**
693
     * Returns an array consisting of the characters in the string.
694
     *
695
     * EXAMPLE: <code>
696
     * s('fòôbàř')->chars(); // ['f', 'ò', 'ô', 'b', 'à', 'ř']
697
     * </code>
698
     *
699
     * @psalm-mutation-free
700
     *
701
     * @return string[]
702
     *                  <p>An array of string chars.</p>
703
     */
704
    public function chars(): array
705
    {
706
        /** @var string[] */
707
        return $this->utf8::str_split($this->str);
14✔
708
    }
709

710
    /**
711
     * Splits the string into chunks of Stringy objects.
712
     *
713
     * EXAMPLE: <code>
714
     * s('foobar')->chunk(3); // ['foo', 'bar']
715
     * </code>
716
     *
717
     * @param int $length [optional] <p>Max character length of each array element.</p>
718
     *
719
     * @psalm-mutation-free
720
     *
721
     * @return static[]
722
     *                  <p>An array of Stringy objects.</p>
723
     *
724
     * @phpstan-return array<int,static>
725
     */
726
    public function chunk(int $length = 1): array
727
    {
728
        if ($length < 1) {
13✔
729
            throw new \InvalidArgumentException('The chunk length must be greater than zero.');
×
730
        }
731

732
        if ($this->str === '') {
13✔
733
            return [];
2✔
734
        }
735

736
        $chunks = $this->utf8::str_split($this->str, $length);
11✔
737

738
        foreach ($chunks as &$value) {
11✔
739
            $value = static::create($value, $this->encoding);
11✔
740
        }
741

742
        /** @noinspection PhpSillyAssignmentInspection */
743
        /** @var static[] $chunks */
744
        $chunks = $chunks;
11✔
745

746
        return $chunks;
11✔
747
    }
748

749
    /**
750
     * Splits the string into chunks of Stringy objects collection.
751
     *
752
     * EXAMPLE: <code>
753
     * </code>
754
     *
755
     * @param int $length [optional] <p>Max character length of each array element.</p>
756
     *
757
     * @psalm-mutation-free
758
     *
759
     * @return CollectionStringy|static[]
760
     *                                    <p>An collection of Stringy objects.</p>
761
     *
762
     * @phpstan-return CollectionStringy<int,static>
763
     */
764
    public function chunkCollection(int $length = 1): CollectionStringy
765
    {
766
        /**
767
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the collection class
768
         */
769
        return CollectionStringy::create(
7✔
770
            $this->chunk($length)
7✔
771
        );
7✔
772
    }
773

774
    /**
775
     * Trims the string and replaces consecutive whitespace characters with a
776
     * single space. This includes tabs and newline characters, as well as
777
     * multibyte whitespace such as the thin space and ideographic space.
778
     *
779
     * EXAMPLE: <code>
780
     * s('   Ο     συγγραφέας  ')->collapseWhitespace(); // 'Ο συγγραφέας'
781
     * </code>
782
     *
783
     * @psalm-mutation-free
784
     *
785
     * @return static
786
     *                <p>Object with a trimmed $str and condensed whitespace.</p>
787
     */
788
    public function collapseWhitespace(): self
789
    {
790
        return static::create(
39✔
791
            $this->utf8::collapse_whitespace($this->str),
39✔
792
            $this->encoding
39✔
793
        );
39✔
794
    }
795

796
    /**
797
     * Returns true if the string contains $needle, false otherwise. By default
798
     * the comparison is case-sensitive, but can be made insensitive by setting
799
     * $caseSensitive to false.
800
     *
801
     * EXAMPLE: <code>
802
     * s('Ο συγγραφέας είπε')->contains('συγγραφέας'); // true
803
     * </code>
804
     *
805
     * @param string $needle        <p>Substring to look for.</p>
806
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
807
     *
808
     * @psalm-mutation-free
809
     *
810
     * @return bool
811
     *              <p>Whether or not $str contains $needle.</p>
812
     */
813
    public function contains(string $needle, bool $caseSensitive = true): bool
814
    {
815
        return $this->utf8::str_contains(
63✔
816
            $this->str,
63✔
817
            $needle,
63✔
818
            $caseSensitive
63✔
819
        );
63✔
820
    }
821

822
    /**
823
     * Returns true if the string contains all $needles, false otherwise. By
824
     * default the comparison is case-sensitive, but can be made insensitive by
825
     * setting $caseSensitive to false.
826
     *
827
     * EXAMPLE: <code>
828
     * s('foo & bar')->containsAll(['foo', 'bar']); // true
829
     * </code>
830
     *
831
     * @param string[] $needles       <p>SubStrings to look for.</p>
832
     * @param bool     $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
833
     *
834
     * @psalm-mutation-free
835
     *
836
     * @return bool
837
     *              <p>Whether or not $str contains $needle.</p>
838
     */
839
    public function containsAll(array $needles, bool $caseSensitive = true): bool
840
    {
841
        return $this->utf8::str_contains_all(
131✔
842
            $this->str,
131✔
843
            $needles,
131✔
844
            $caseSensitive
131✔
845
        );
131✔
846
    }
847

848
    /**
849
     * Returns true if the string contains any $needles, false otherwise. By
850
     * default the comparison is case-sensitive, but can be made insensitive by
851
     * setting $caseSensitive to false.
852
     *
853
     * EXAMPLE: <code>
854
     * s('str contains foo')->containsAny(['foo', 'bar']); // true
855
     * </code>
856
     *
857
     * @param string[] $needles       <p>SubStrings to look for.</p>
858
     * @param bool     $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
859
     *
860
     * @psalm-mutation-free
861
     *
862
     * @return bool
863
     *              <p>Whether or not $str contains $needle.</p>
864
     */
865
    public function containsAny(array $needles, bool $caseSensitive = true): bool
866
    {
867
        return $this->utf8::str_contains_any(
129✔
868
            $this->str,
129✔
869
            $needles,
129✔
870
            $caseSensitive
129✔
871
        );
129✔
872
    }
873

874
    /**
875
     * Checks if string starts with "BOM" (Byte Order Mark Character) character.
876
     *
877
     * EXAMPLE: <code>s("\xef\xbb\xbf foobar")->containsBom(); // true</code>
878
     *
879
     * @psalm-mutation-free
880
     *
881
     * @return bool
882
     *              <strong>true</strong> if the string has BOM at the start,<br>
883
     *              <strong>false</strong> otherwise
884
     */
885
    public function containsBom(): bool
886
    {
887
        return $this->utf8::string_has_bom($this->str);
×
888
    }
889

890
    /**
891
     * Returns the length of the string, implementing the countable interface.
892
     *
893
     * EXAMPLE: <code>
894
     * </code>
895
     *
896
     * @psalm-mutation-free
897
     *
898
     * @return int
899
     *             <p>The number of characters in the string, given the encoding.</p>
900
     */
901
    public function count(): int
902
    {
903
        return $this->length();
3✔
904
    }
905

906
    /**
907
     * Returns the number of occurrences of $substring in the given string.
908
     * By default, the comparison is case-sensitive, but can be made insensitive
909
     * by setting $caseSensitive to false.
910
     *
911
     * EXAMPLE: <code>
912
     * s('Ο συγγραφέας είπε')->countSubstr('α'); // 2
913
     * </code>
914
     *
915
     * @param string $substring     <p>The substring to search for.</p>
916
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
917
     *
918
     * @psalm-mutation-free
919
     *
920
     * @return int
921
     */
922
    public function countSubstr(string $substring, bool $caseSensitive = true): int
923
    {
924
        return $this->utf8::substr_count_simple(
45✔
925
            $this->str,
45✔
926
            $substring,
45✔
927
            $caseSensitive,
45✔
928
            $this->encoding
45✔
929
        );
45✔
930
    }
931

932
    /**
933
     * Calculates the crc32 polynomial of a string.
934
     *
935
     * EXAMPLE: <code>
936
     * </code>
937
     *
938
     * @psalm-mutation-free
939
     *
940
     * @return int
941
     */
942
    public function crc32(): int
943
    {
944
        return \crc32($this->str);
2✔
945
    }
946

947
    /**
948
     * Creates a Stringy object and assigns both str and encoding properties
949
     * the supplied values. $str is cast to a string prior to assignment, and if
950
     * $encoding is not specified, it defaults to mb_internal_encoding(). It
951
     * then returns the initialized object. Throws an InvalidArgumentException
952
     * if the first argument is an array or object without a __toString method.
953
     *
954
     * @param mixed  $str      [optional] <p>Value to modify, after being cast to string. Default: ''</p>
955
     * @param string $encoding [optional] <p>The character encoding. Fallback: 'UTF-8'</p>
956
     *
957
     * @throws \InvalidArgumentException
958
     *                                   <p>if an array or object without a
959
     *                                   __toString method is passed as the first argument</p>
960
     *
961
     * @return static
962
     *                <p>A Stringy object.</p>
963
     */
964
    public static function create($str = '', ?string $encoding = null): self
965
    {
966
        return new static($str, $encoding);
3,624✔
967
    }
968

969
    /**
970
     * One-way string encryption (hashing).
971
     *
972
     * Hash the string using the standard Unix DES-based algorithm or an
973
     * alternative algorithm that may be available on the system.
974
     *
975
     * PS: if you need encrypt / decrypt, please use ```static::encrypt($password)```
976
     *     and ```static::decrypt($password)```
977
     *
978
     * EXAMPLE: <code>
979
     * </code>
980
     *
981
     * @param string $salt <p>A salt string to base the hashing on.</p>
982
     *
983
     * @psalm-mutation-free
984
     *
985
     * @return static
986
     */
987
    public function crypt(string $salt): self
988
    {
989
        return new static(
3✔
990
            \crypt(
3✔
991
                $this->str,
3✔
992
                $salt
3✔
993
            ),
3✔
994
            $this->encoding
3✔
995
        );
3✔
996
    }
997

998
    /**
999
     * Returns a lowercase and trimmed string separated by dashes. Dashes are
1000
     * inserted before uppercase characters (with the exception of the first
1001
     * character of the string), and in place of spaces as well as underscores.
1002
     *
1003
     * EXAMPLE: <code>
1004
     * s('fooBar')->dasherize(); // 'foo-bar'
1005
     * </code>
1006
     *
1007
     * @psalm-mutation-free
1008
     *
1009
     * @return static
1010
     *                <p>Object with a dasherized $str</p>
1011
     */
1012
    public function dasherize(): self
1013
    {
1014
        return static::create(
57✔
1015
            $this->utf8::str_dasherize($this->str),
57✔
1016
            $this->encoding
57✔
1017
        );
57✔
1018
    }
1019

1020
    /**
1021
     * Decrypt the string.
1022
     *
1023
     * EXAMPLE: <code>
1024
     * </code>
1025
     *
1026
     * @param string $password The key for decrypting
1027
     *
1028
     * @psalm-mutation-free
1029
     *
1030
     * @return static
1031
     */
1032
    public function decrypt(string $password): self
1033
    {
1034
        /**
1035
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to vendor stuff
1036
         */
1037
        return new static(
5✔
1038
            Crypto::decryptWithPassword($this->str, $password),
5✔
1039
            $this->encoding
5✔
1040
        );
5✔
1041
    }
1042

1043
    /**
1044
     * Returns a lowercase and trimmed string separated by the given delimiter.
1045
     * Delimiters are inserted before uppercase characters (with the exception
1046
     * of the first character of the string), and in place of spaces, dashes,
1047
     * and underscores. Alpha delimiters are not converted to lowercase.
1048
     *
1049
     * EXAMPLE: <code>
1050
     * s('fooBar')->delimit('::'); // 'foo::bar'
1051
     * </code>
1052
     *
1053
     * @param string $delimiter <p>Sequence used to separate parts of the string.</p>
1054
     *
1055
     * @psalm-mutation-free
1056
     *
1057
     * @return static
1058
     *                <p>Object with a delimited $str.</p>
1059
     */
1060
    public function delimit(string $delimiter): self
1061
    {
1062
        return static::create(
90✔
1063
            $this->utf8::str_delimit($this->str, $delimiter),
90✔
1064
            $this->encoding
90✔
1065
        );
90✔
1066
    }
1067

1068
    /**
1069
     * Encode the given string into the given $encoding + set the internal character encoding.
1070
     *
1071
     * EXAMPLE: <code>
1072
     * </code>
1073
     *
1074
     * @param string $new_encoding         <p>The desired character encoding.</p>
1075
     * @param bool   $auto_detect_encoding [optional] <p>Auto-detect the current string-encoding</p>
1076
     *
1077
     * @psalm-mutation-free
1078
     *
1079
     * @return static
1080
     */
1081
    public function encode(string $new_encoding, bool $auto_detect_encoding = false): self
1082
    {
1083
        if ($auto_detect_encoding) {
2✔
1084
            $str = $this->utf8::encode(
1✔
1085
                $new_encoding,
1✔
1086
                $this->str
1✔
1087
            );
1✔
1088
        } else {
1089
            $str = $this->utf8::encode(
1✔
1090
                $new_encoding,
1✔
1091
                $this->str,
1✔
1092
                false,
1✔
1093
                $this->encoding
1✔
1094
            );
1✔
1095
        }
1096

1097
        return new static($str, $new_encoding);
2✔
1098
    }
1099

1100
    /**
1101
     * Encrypt the string.
1102
     *
1103
     * EXAMPLE: <code>
1104
     * </code>
1105
     *
1106
     * @param string $password <p>The key for encrypting</p>
1107
     *
1108
     * @psalm-mutation-free
1109
     *
1110
     * @return static
1111
     */
1112
    public function encrypt(string $password): self
1113
    {
1114
        /**
1115
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to vendor stuff
1116
         */
1117
        return new static(
4✔
1118
            Crypto::encryptWithPassword($this->str, $password),
4✔
1119
            $this->encoding
4✔
1120
        );
4✔
1121
    }
1122

1123
    /**
1124
     * Returns true if the string ends with $substring, false otherwise. By
1125
     * default, the comparison is case-sensitive, but can be made insensitive
1126
     * by setting $caseSensitive to false.
1127
     *
1128
     * EXAMPLE: <code>
1129
     * s('fòôbàř')->endsWith('bàř', true); // true
1130
     * </code>
1131
     *
1132
     * @param string $substring     <p>The substring to look for.</p>
1133
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
1134
     *
1135
     * @psalm-mutation-free
1136
     *
1137
     * @return bool
1138
     *              <p>Whether or not $str ends with $substring.</p>
1139
     */
1140
    public function endsWith(string $substring, bool $caseSensitive = true): bool
1141
    {
1142
        if ($caseSensitive) {
97✔
1143
            return $this->utf8::str_ends_with($this->str, $substring);
53✔
1144
        }
1145

1146
        return $this->utf8::str_iends_with($this->str, $substring);
44✔
1147
    }
1148

1149
    /**
1150
     * Returns true if the string ends with any of $substrings, false otherwise.
1151
     * By default, the comparison is case-sensitive, but can be made insensitive
1152
     * by setting $caseSensitive to false.
1153
     *
1154
     * EXAMPLE: <code>
1155
     * s('fòôbàř')->endsWithAny(['bàř', 'baz'], true); // true
1156
     * </code>
1157
     *
1158
     * @param string[] $substrings    <p>Substrings to look for.</p>
1159
     * @param bool     $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
1160
     *
1161
     * @psalm-mutation-free
1162
     *
1163
     * @return bool
1164
     *              <p>Whether or not $str ends with $substring.</p>
1165
     */
1166
    public function endsWithAny(array $substrings, bool $caseSensitive = true): bool
1167
    {
1168
        if ($caseSensitive) {
33✔
1169
            return $this->utf8::str_ends_with_any($this->str, $substrings);
21✔
1170
        }
1171

1172
        return $this->utf8::str_iends_with_any($this->str, $substrings);
12✔
1173
    }
1174

1175
    /**
1176
     * Ensures that the string begins with $substring. If it doesn't, it's
1177
     * prepended.
1178
     *
1179
     * EXAMPLE: <code>
1180
     * s('foobar')->ensureLeft('http://'); // 'http://foobar'
1181
     * </code>
1182
     *
1183
     * @param string $substring <p>The substring to add if not present.</p>
1184
     *
1185
     * @psalm-mutation-free
1186
     *
1187
     * @return static
1188
     *                <p>Object with its $str prefixed by the $substring.</p>
1189
     */
1190
    public function ensureLeft(string $substring): self
1191
    {
1192
        return static::create(
30✔
1193
            $this->utf8::str_ensure_left($this->str, $substring),
30✔
1194
            $this->encoding
30✔
1195
        );
30✔
1196
    }
1197

1198
    /**
1199
     * Ensures that the string ends with $substring. If it doesn't, it's appended.
1200
     *
1201
     * EXAMPLE: <code>
1202
     * s('foobar')->ensureRight('.com'); // 'foobar.com'
1203
     * </code>
1204
     *
1205
     * @param string $substring <p>The substring to add if not present.</p>
1206
     *
1207
     * @psalm-mutation-free
1208
     *
1209
     * @return static
1210
     *                <p>Object with its $str suffixed by the $substring.</p>
1211
     */
1212
    public function ensureRight(string $substring): self
1213
    {
1214
        return static::create(
30✔
1215
            $this->utf8::str_ensure_right($this->str, $substring),
30✔
1216
            $this->encoding
30✔
1217
        );
30✔
1218
    }
1219

1220
    /**
1221
     * Create a escape html version of the string via "htmlspecialchars()".
1222
     *
1223
     * EXAMPLE: <code>
1224
     * s('<∂∆ onerror="alert(xss)">')->escape(); // '&lt;∂∆ onerror=&quot;alert(xss)&quot;&gt;'
1225
     * </code>
1226
     *
1227
     * @psalm-mutation-free
1228
     *
1229
     * @return static
1230
     */
1231
    public function escape(): self
1232
    {
1233
        return static::create(
12✔
1234
            $this->utf8::htmlspecialchars(
12✔
1235
                $this->str,
12✔
1236
                \ENT_QUOTES | \ENT_SUBSTITUTE,
12✔
1237
                $this->encoding
12✔
1238
            ),
12✔
1239
            $this->encoding
12✔
1240
        );
12✔
1241
    }
1242

1243
    /**
1244
     * Split a string by a string.
1245
     *
1246
     * EXAMPLE: <code>
1247
     * </code>
1248
     *
1249
     * @param string $delimiter <p>The boundary string</p>
1250
     * @param int    $limit     [optional] <p>The maximum number of elements in the exploded
1251
     *                          collection.</p>
1252
     *
1253
     *   - If limit is set and positive, the returned collection will contain a maximum of limit elements with the last
1254
     *   element containing the rest of string.
1255
     *   - If the limit parameter is negative, all components except the last -limit are returned.
1256
     *   - If the limit parameter is zero, then this is treated as 1
1257
     *
1258
     * @psalm-mutation-free
1259
     *
1260
     * @return array<int,static>
1261
     */
1262
    public function explode(string $delimiter, int $limit = \PHP_INT_MAX): array
1263
    {
1264
        if ($this->str === '') {
3✔
1265
            return [];
×
1266
        }
1267

1268
        /** @phpstan-ignore-next-line - FP -> non-empty-string is already checked */
1269
        $strings = \explode($delimiter, $this->str, $limit);
3✔
1270
        /** @phpstan-ignore-next-line - if "$delimiter" is an empty string, then "explode()" will return "false" */
1271
        if ($strings === false) {
3✔
1272
            $strings = [];
×
1273
        }
1274

1275
        return \array_map(
3✔
1276
            function ($str) {
3✔
1277
                return new static($str, $this->encoding);
3✔
1278
            },
3✔
1279
            $strings
3✔
1280
        );
3✔
1281
    }
1282

1283
    /**
1284
     * Split a string by a string.
1285
     *
1286
     * EXAMPLE: <code>
1287
     * </code>
1288
     *
1289
     * @param string $delimiter <p>The boundary string</p>
1290
     * @param int    $limit     [optional] <p>The maximum number of elements in the exploded
1291
     *                          collection.</p>
1292
     *
1293
     *   - If limit is set and positive, the returned collection will contain a maximum of limit elements with the last
1294
     *   element containing the rest of string.
1295
     *   - If the limit parameter is negative, all components except the last -limit are returned.
1296
     *   - If the limit parameter is zero, then this is treated as 1
1297
     *
1298
     * @psalm-mutation-free
1299
     *
1300
     * @return CollectionStringy|static[]
1301
     *                                    <p>An collection of Stringy objects.</p>
1302
     *
1303
     * @phpstan-return CollectionStringy<int,static>
1304
     */
1305
    public function explodeCollection(string $delimiter, int $limit = \PHP_INT_MAX): CollectionStringy
1306
    {
1307
        /**
1308
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the collection class
1309
         */
1310
        return CollectionStringy::create(
1✔
1311
            $this->explode($delimiter, $limit)
1✔
1312
        );
1✔
1313
    }
1314

1315
    /**
1316
     * Create an extract from a sentence, so if the search-string was found, it try to centered in the output.
1317
     *
1318
     * EXAMPLE: <code>
1319
     * $sentence = 'This is only a Fork of Stringy, take a look at the new features.';
1320
     * s($sentence)->extractText('Stringy'); // '...Fork of Stringy...'
1321
     * </code>
1322
     *
1323
     * @param string   $search
1324
     * @param int|null $length                 [optional] <p>Default: null === text->length / 2</p>
1325
     * @param string   $replacerForSkippedText [optional] <p>Default: …</p>
1326
     *
1327
     * @psalm-mutation-free
1328
     *
1329
     * @return static
1330
     */
1331
    public function extractText(string $search = '', ?int $length = null, string $replacerForSkippedText = '…'): self
1332
    {
1333
        return static::create(
2✔
1334
            $this->utf8::extract_text(
2✔
1335
                $this->str,
2✔
1336
                $search,
2✔
1337
                $length,
2✔
1338
                $replacerForSkippedText,
2✔
1339
                $this->encoding
2✔
1340
            ),
2✔
1341
            $this->encoding
2✔
1342
        );
2✔
1343
    }
1344

1345
    /**
1346
     * Returns the first $n characters of the string.
1347
     *
1348
     * EXAMPLE: <code>
1349
     * s('fòôbàř')->first(3); // 'fòô'
1350
     * </code>
1351
     *
1352
     * @param int $n <p>Number of characters to retrieve from the start.</p>
1353
     *
1354
     * @psalm-mutation-free
1355
     *
1356
     * @return static
1357
     *                <p>Object with its $str being the first $n chars.</p>
1358
     */
1359
    public function first(int $n): self
1360
    {
1361
        if ($n <= 0) {
37✔
1362
            return static::create('', $this->encoding);
12✔
1363
        }
1364

1365
        return static::create(
25✔
1366
            $this->utf8::first_char($this->str, $n, $this->encoding),
25✔
1367
            $this->encoding
25✔
1368
        );
25✔
1369
    }
1370

1371
    /**
1372
     * Return a formatted string via sprintf + named parameters via array syntax.
1373
     *
1374
     * <p>
1375
     * <br>
1376
     * It will use "sprintf()" so you can use e.g.:
1377
     * <br>
1378
     * <br><pre>s('There are %d monkeys in the %s')->format(5, 'tree');</pre>
1379
     * <br>
1380
     * <br><pre>s('There are %2$d monkeys in the %1$s')->format('tree', 5);</pre>
1381
     * <br>
1382
     * <br>
1383
     * But you can also use named parameter via array syntax e.g.:
1384
     * <br>
1385
     * <br><pre>s('There are %:count monkeys in the %:location')->format(['count' => 5, 'location' => 'tree');</pre>
1386
     * </p>
1387
     *
1388
     * EXAMPLE: <code>
1389
     * $input = 'one: %2$d, %1$s: 2, %:text_three: %3$d';
1390
     * s($input)->format(['text_three' => '%4$s'], 'two', 1, 3, 'three'); // 'One: 1, two: 2, three: 3'
1391
     * </code>
1392
     *
1393
     * @param mixed ...$args [optional]
1394
     *
1395
     * @psalm-mutation-free
1396
     *
1397
     * @return static
1398
     *                <p>A Stringy object produced according to the formatting string
1399
     *                format.</p>
1400
     */
1401
    public function format(...$args): self
1402
    {
1403
        // init
1404
        $str = $this->str;
10✔
1405

1406
        if (\strpos($this->str, '%:') !== false) {
10✔
1407
            $offset = null;
8✔
1408
            $replacement = null;
8✔
1409
            /** @noinspection AlterInForeachInspection */
1410
            foreach ($args as $key => &$arg) {
8✔
1411
                if (!\is_array($arg)) {
8✔
1412
                    continue;
4✔
1413
                }
1414

1415
                foreach ($arg as $name => $param) {
8✔
1416
                    $name = (string) $name;
8✔
1417

1418
                    if (\strpos($name, '%:') !== 0) {
8✔
1419
                        $nameTmp = '%:' . $name;
8✔
1420
                    } else {
1421
                        $nameTmp = $name;
×
1422
                    }
1423

1424
                    if ($offset === null) {
8✔
1425
                        $offset = \strpos($str, $nameTmp);
8✔
1426
                    } else {
1427
                        $offset = \strpos($str, $nameTmp, (int) $offset + \strlen((string) $replacement));
6✔
1428
                    }
1429
                    if ($offset === false) {
8✔
1430
                        continue;
4✔
1431
                    }
1432

1433
                    unset($arg[$name]);
8✔
1434

1435
                    $str = \substr_replace($str, (string) $param, (int) $offset, \strlen($nameTmp));
8✔
1436
                }
1437

1438
                unset($args[$key]);
8✔
1439
            }
1440
        }
1441

1442
        $str = \str_replace('%:', '%%:', $str);
10✔
1443

1444
        return static::create(
10✔
1445
            \sprintf($str, ...$args),
10✔
1446
            $this->encoding
10✔
1447
        );
10✔
1448
    }
1449

1450
    /**
1451
     * Returns the encoding used by the Stringy object.
1452
     *
1453
     * EXAMPLE: <code>
1454
     * s('fòôbàř', 'UTF-8')->getEncoding(); // 'UTF-8'
1455
     * </code>
1456
     *
1457
     * @psalm-mutation-free
1458
     *
1459
     * @return string
1460
     *                <p>The current value of the $encoding property.</p>
1461
     */
1462
    public function getEncoding(): string
1463
    {
1464
        return $this->encoding;
25✔
1465
    }
1466

1467
    /**
1468
     * Returns a new ArrayIterator, thus implementing the IteratorAggregate
1469
     * interface. The ArrayIterator's constructor is passed an array of chars
1470
     * in the multibyte string. This enables the use of foreach with instances
1471
     * of Stringy\Stringy.
1472
     *
1473
     * EXAMPLE: <code>
1474
     * </code>
1475
     *
1476
     * @psalm-mutation-free
1477
     *
1478
     * @return \ArrayIterator
1479
     *                        <p>An iterator for the characters in the string.</p>
1480
     *
1481
     * @phpstan-return \ArrayIterator<array-key,string>
1482
     */
1483
    public function getIterator(): \ArrayIterator
1484
    {
1485
        return new \ArrayIterator($this->chars());
3✔
1486
    }
1487

1488
    /**
1489
     * Wrap the string after an exact number of characters.
1490
     *
1491
     * EXAMPLE: <code>
1492
     * </code>
1493
     *
1494
     * @param int    $width <p>Number of characters at which to wrap.</p>
1495
     * @param string $break [optional] <p>Character used to break the string. | Default: "\n"</p>
1496
     *
1497
     * @psalm-mutation-free
1498
     *
1499
     * @return static
1500
     */
1501
    public function hardWrap($width, $break = "\n"): self
1502
    {
1503
        return $this->lineWrap($width, $break, false);
2✔
1504
    }
1505

1506
    /**
1507
     * Returns true if the string contains a lower case char, false otherwise
1508
     *
1509
     * EXAMPLE: <code>
1510
     * s('fòôbàř')->hasLowerCase(); // true
1511
     * </code>
1512
     *
1513
     * @psalm-mutation-free
1514
     *
1515
     * @return bool
1516
     *              <p>Whether or not the string contains a lower case character.</p>
1517
     */
1518
    public function hasLowerCase(): bool
1519
    {
1520
        return $this->utf8::has_lowercase($this->str);
36✔
1521
    }
1522

1523
    /**
1524
     * Returns true if the string contains an upper case char, false otherwise.
1525
     *
1526
     * EXAMPLE: <code>
1527
     * s('fòôbàř')->hasUpperCase(); // false
1528
     * </code>
1529
     *
1530
     * @psalm-mutation-free
1531
     *
1532
     * @return bool
1533
     *              <p>Whether or not the string contains an upper case character.</p>
1534
     */
1535
    public function hasUpperCase(): bool
1536
    {
1537
        return $this->utf8::has_uppercase($this->str);
36✔
1538
    }
1539

1540
    /**
1541
     * Generate a hash value (message digest).
1542
     *
1543
     * EXAMPLE: <code>
1544
     * </code>
1545
     *
1546
     * @see https://php.net/manual/en/function.hash.php
1547
     *
1548
     * @param string $algorithm
1549
     *                          <p>Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)</p>
1550
     *
1551
     * @psalm-mutation-free
1552
     *
1553
     * @return static
1554
     */
1555
    public function hash($algorithm): self
1556
    {
1557
        return static::create(\hash($algorithm, $this->str), $this->encoding);
8✔
1558
    }
1559

1560
    /**
1561
     * Decode the string from hex.
1562
     *
1563
     * EXAMPLE: <code>
1564
     * </code>
1565
     *
1566
     * @psalm-mutation-free
1567
     *
1568
     * @return static
1569
     */
1570
    public function hexDecode(): self
1571
    {
1572
        $string = \preg_replace_callback(
2✔
1573
            '/\\\\x([0-9A-Fa-f]+)/',
2✔
1574
            function (array $matched) {
2✔
1575
                return (string) $this->utf8::hex_to_chr($matched[1]);
2✔
1576
            },
2✔
1577
            $this->str
2✔
1578
        );
2✔
1579

1580
        return static::create(
2✔
1581
            $string,
2✔
1582
            $this->encoding
2✔
1583
        );
2✔
1584
    }
1585

1586
    /**
1587
     * Encode string to hex.
1588
     *
1589
     * EXAMPLE: <code>
1590
     * </code>
1591
     *
1592
     * @psalm-mutation-free
1593
     *
1594
     * @return static
1595
     */
1596
    public function hexEncode(): self
1597
    {
1598
        $string = \array_reduce(
2✔
1599
            $this->chars(),
2✔
1600
            function (string $str, string $char) {
2✔
1601
                return $str . $this->utf8::chr_to_hex($char);
2✔
1602
            },
2✔
1603
            ''
2✔
1604
        );
2✔
1605

1606
        return static::create(
2✔
1607
            $string,
2✔
1608
            $this->encoding
2✔
1609
        );
2✔
1610
    }
1611

1612
    /**
1613
     * Convert all HTML entities to their applicable characters.
1614
     *
1615
     * EXAMPLE: <code>
1616
     * s('&amp;')->htmlDecode(); // '&'
1617
     * </code>
1618
     *
1619
     * @param int $flags [optional] <p>
1620
     *                   A bitmask of one or more of the following flags, which specify how to handle quotes and
1621
     *                   which document type to use. The default is ENT_COMPAT.
1622
     *                   <table>
1623
     *                   Available <i>flags</i> constants
1624
     *                   <tr valign="top">
1625
     *                   <td>Constant Name</td>
1626
     *                   <td>Description</td>
1627
     *                   </tr>
1628
     *                   <tr valign="top">
1629
     *                   <td><b>ENT_COMPAT</b></td>
1630
     *                   <td>Will convert double-quotes and leave single-quotes alone.</td>
1631
     *                   </tr>
1632
     *                   <tr valign="top">
1633
     *                   <td><b>ENT_QUOTES</b></td>
1634
     *                   <td>Will convert both double and single quotes.</td>
1635
     *                   </tr>
1636
     *                   <tr valign="top">
1637
     *                   <td><b>ENT_NOQUOTES</b></td>
1638
     *                   <td>Will leave both double and single quotes unconverted.</td>
1639
     *                   </tr>
1640
     *                   <tr valign="top">
1641
     *                   <td><b>ENT_HTML401</b></td>
1642
     *                   <td>
1643
     *                   Handle code as HTML 4.01.
1644
     *                   </td>
1645
     *                   </tr>
1646
     *                   <tr valign="top">
1647
     *                   <td><b>ENT_XML1</b></td>
1648
     *                   <td>
1649
     *                   Handle code as XML 1.
1650
     *                   </td>
1651
     *                   </tr>
1652
     *                   <tr valign="top">
1653
     *                   <td><b>ENT_XHTML</b></td>
1654
     *                   <td>
1655
     *                   Handle code as XHTML.
1656
     *                   </td>
1657
     *                   </tr>
1658
     *                   <tr valign="top">
1659
     *                   <td><b>ENT_HTML5</b></td>
1660
     *                   <td>
1661
     *                   Handle code as HTML 5.
1662
     *                   </td>
1663
     *                   </tr>
1664
     *                   </table>
1665
     *                   </p>
1666
     *
1667
     * @psalm-mutation-free
1668
     *
1669
     * @return static
1670
     *                <p>Object with the resulting $str after being html decoded.</p>
1671
     */
1672
    public function htmlDecode(int $flags = \ENT_COMPAT): self
1673
    {
1674
        return static::create(
15✔
1675
            $this->utf8::html_entity_decode(
15✔
1676
                $this->str,
15✔
1677
                $flags,
15✔
1678
                $this->encoding
15✔
1679
            ),
15✔
1680
            $this->encoding
15✔
1681
        );
15✔
1682
    }
1683

1684
    /**
1685
     * Convert all applicable characters to HTML entities.
1686
     *
1687
     * EXAMPLE: <code>
1688
     * s('&')->htmlEncode(); // '&amp;'
1689
     * </code>
1690
     *
1691
     * @param int $flags [optional] <p>
1692
     *                   A bitmask of one or more of the following flags, which specify how to handle quotes and
1693
     *                   which document type to use. The default is ENT_COMPAT.
1694
     *                   <table>
1695
     *                   Available <i>flags</i> constants
1696
     *                   <tr valign="top">
1697
     *                   <td>Constant Name</td>
1698
     *                   <td>Description</td>
1699
     *                   </tr>
1700
     *                   <tr valign="top">
1701
     *                   <td><b>ENT_COMPAT</b></td>
1702
     *                   <td>Will convert double-quotes and leave single-quotes alone.</td>
1703
     *                   </tr>
1704
     *                   <tr valign="top">
1705
     *                   <td><b>ENT_QUOTES</b></td>
1706
     *                   <td>Will convert both double and single quotes.</td>
1707
     *                   </tr>
1708
     *                   <tr valign="top">
1709
     *                   <td><b>ENT_NOQUOTES</b></td>
1710
     *                   <td>Will leave both double and single quotes unconverted.</td>
1711
     *                   </tr>
1712
     *                   <tr valign="top">
1713
     *                   <td><b>ENT_HTML401</b></td>
1714
     *                   <td>
1715
     *                   Handle code as HTML 4.01.
1716
     *                   </td>
1717
     *                   </tr>
1718
     *                   <tr valign="top">
1719
     *                   <td><b>ENT_XML1</b></td>
1720
     *                   <td>
1721
     *                   Handle code as XML 1.
1722
     *                   </td>
1723
     *                   </tr>
1724
     *                   <tr valign="top">
1725
     *                   <td><b>ENT_XHTML</b></td>
1726
     *                   <td>
1727
     *                   Handle code as XHTML.
1728
     *                   </td>
1729
     *                   </tr>
1730
     *                   <tr valign="top">
1731
     *                   <td><b>ENT_HTML5</b></td>
1732
     *                   <td>
1733
     *                   Handle code as HTML 5.
1734
     *                   </td>
1735
     *                   </tr>
1736
     *                   </table>
1737
     *                   </p>
1738
     *
1739
     * @psalm-mutation-free
1740
     *
1741
     * @return static
1742
     *                <p>Object with the resulting $str after being html encoded.</p>
1743
     */
1744
    public function htmlEncode(int $flags = \ENT_COMPAT): self
1745
    {
1746
        return static::create(
15✔
1747
            $this->utf8::htmlentities(
15✔
1748
                $this->str,
15✔
1749
                $flags,
15✔
1750
                $this->encoding
15✔
1751
            ),
15✔
1752
            $this->encoding
15✔
1753
        );
15✔
1754
    }
1755

1756
    /**
1757
     * Capitalizes the first word of the string, replaces underscores with
1758
     * spaces, and strips '_id'.
1759
     *
1760
     * EXAMPLE: <code>
1761
     * s('author_id')->humanize(); // 'Author'
1762
     * </code>
1763
     *
1764
     * @psalm-mutation-free
1765
     *
1766
     * @return static
1767
     *                <p>Object with a humanized $str.</p>
1768
     */
1769
    public function humanize(): self
1770
    {
1771
        return static::create(
9✔
1772
            $this->utf8::str_humanize($this->str),
9✔
1773
            $this->encoding
9✔
1774
        );
9✔
1775
    }
1776

1777
    /**
1778
     * Determine if the current string exists in another string. By
1779
     * default, the comparison is case-sensitive, but can be made insensitive
1780
     * by setting $caseSensitive to false.
1781
     *
1782
     * EXAMPLE: <code>
1783
     * </code>
1784
     *
1785
     * @param string $str           <p>The string to compare against.</p>
1786
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
1787
     *
1788
     * @psalm-mutation-free
1789
     *
1790
     * @return bool
1791
     */
1792
    public function in(string $str, bool $caseSensitive = true): bool
1793
    {
1794
        if ($caseSensitive) {
3✔
1795
            return \strpos($str, $this->str) !== false;
2✔
1796
        }
1797

1798
        return \stripos($str, $this->str) !== false;
1✔
1799
    }
1800

1801
    /**
1802
     * Returns the index of the first occurrence of $needle in the string,
1803
     * and false if not found. Accepts an optional offset from which to begin
1804
     * the search.
1805
     *
1806
     * EXAMPLE: <code>
1807
     * s('string')->indexOf('ing'); // 3
1808
     * </code>
1809
     *
1810
     * @param string $needle <p>Substring to look for.</p>
1811
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
1812
     *
1813
     * @psalm-mutation-free
1814
     *
1815
     * @return false|int
1816
     *                   <p>The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
1817
     */
1818
    public function indexOf(string $needle, int $offset = 0)
1819
    {
1820
        return $this->utf8::strpos(
31✔
1821
            $this->str,
31✔
1822
            $needle,
31✔
1823
            $offset,
31✔
1824
            $this->encoding
31✔
1825
        );
31✔
1826
    }
1827

1828
    /**
1829
     * Returns the index of the first occurrence of $needle in the string,
1830
     * and false if not found. Accepts an optional offset from which to begin
1831
     * the search.
1832
     *
1833
     * EXAMPLE: <code>
1834
     * s('string')->indexOfIgnoreCase('ING'); // 3
1835
     * </code>
1836
     *
1837
     * @param string $needle <p>Substring to look for.</p>
1838
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
1839
     *
1840
     * @psalm-mutation-free
1841
     *
1842
     * @return false|int
1843
     *                   <p>The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
1844
     */
1845
    public function indexOfIgnoreCase(string $needle, int $offset = 0)
1846
    {
1847
        return $this->utf8::stripos(
20✔
1848
            $this->str,
20✔
1849
            $needle,
20✔
1850
            $offset,
20✔
1851
            $this->encoding
20✔
1852
        );
20✔
1853
    }
1854

1855
    /**
1856
     * Returns the index of the last occurrence of $needle in the string,
1857
     * and false if not found. Accepts an optional offset from which to begin
1858
     * the search. Offsets may be negative to count from the last character
1859
     * in the string.
1860
     *
1861
     * EXAMPLE: <code>
1862
     * s('foobarfoo')->indexOfLast('foo'); // 10
1863
     * </code>
1864
     *
1865
     * @param string $needle <p>Substring to look for.</p>
1866
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
1867
     *
1868
     * @psalm-mutation-free
1869
     *
1870
     * @return false|int
1871
     *                   <p>The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
1872
     */
1873
    public function indexOfLast(string $needle, int $offset = 0)
1874
    {
1875
        return $this->utf8::strrpos(
31✔
1876
            $this->str,
31✔
1877
            $needle,
31✔
1878
            $offset,
31✔
1879
            $this->encoding
31✔
1880
        );
31✔
1881
    }
1882

1883
    /**
1884
     * Returns the index of the last occurrence of $needle in the string,
1885
     * and false if not found. Accepts an optional offset from which to begin
1886
     * the search. Offsets may be negative to count from the last character
1887
     * in the string.
1888
     *
1889
     * EXAMPLE: <code>
1890
     * s('fooBarFoo')->indexOfLastIgnoreCase('foo'); // 10
1891
     * </code>
1892
     *
1893
     * @param string $needle <p>Substring to look for.</p>
1894
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
1895
     *
1896
     * @psalm-mutation-free
1897
     *
1898
     * @return false|int
1899
     *                   <p>The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
1900
     */
1901
    public function indexOfLastIgnoreCase(string $needle, int $offset = 0)
1902
    {
1903
        return $this->utf8::strripos(
20✔
1904
            $this->str,
20✔
1905
            $needle,
20✔
1906
            $offset,
20✔
1907
            $this->encoding
20✔
1908
        );
20✔
1909
    }
1910

1911
    /**
1912
     * Inserts $substring into the string at the $index provided.
1913
     *
1914
     * EXAMPLE: <code>
1915
     * s('fòôbř')->insert('à', 4); // 'fòôbàř'
1916
     * </code>
1917
     *
1918
     * @param string $substring <p>String to be inserted.</p>
1919
     * @param int    $index     <p>The index at which to insert the substring.</p>
1920
     *
1921
     * @psalm-mutation-free
1922
     *
1923
     * @return static
1924
     *                <p>Object with the resulting $str after the insertion.</p>
1925
     */
1926
    public function insert(string $substring, int $index): self
1927
    {
1928
        return static::create(
24✔
1929
            $this->utf8::str_insert(
24✔
1930
                $this->str,
24✔
1931
                $substring,
24✔
1932
                $index,
24✔
1933
                $this->encoding
24✔
1934
            ),
24✔
1935
            $this->encoding
24✔
1936
        );
24✔
1937
    }
1938

1939
    /**
1940
     * Returns true if the string contains the $pattern, otherwise false.
1941
     *
1942
     * WARNING: Asterisks ("*") are translated into (".*") zero-or-more regular
1943
     * expression wildcards.
1944
     *
1945
     * EXAMPLE: <code>
1946
     * s('Foo\\Bar\\Lall')->is('*\\Bar\\*'); // true
1947
     * </code>
1948
     *
1949
     * @credit Originally from Laravel, thanks Taylor.
1950
     *
1951
     * @param string $pattern <p>The string or pattern to match against.</p>
1952
     *
1953
     * @psalm-mutation-free
1954
     *
1955
     * @return bool
1956
     *              <p>Whether or not we match the provided pattern.</p>
1957
     */
1958
    public function is(string $pattern): bool
1959
    {
1960
        if ($this->toString() === $pattern) {
26✔
1961
            return true;
2✔
1962
        }
1963

1964
        $quotedPattern = \preg_quote($pattern, '/');
24✔
1965
        $replaceWildCards = \str_replace('\*', '.*', $quotedPattern);
24✔
1966

1967
        return $this->matchesPattern('^' . $replaceWildCards . '\z');
24✔
1968
    }
1969

1970
    /**
1971
     * Returns true if the string contains only alphabetic chars, false otherwise.
1972
     *
1973
     * EXAMPLE: <code>
1974
     * s('丹尼爾')->isAlpha(); // true
1975
     * </code>
1976
     *
1977
     * @psalm-mutation-free
1978
     *
1979
     * @return bool
1980
     *              <p>Whether or not $str contains only alphabetic chars.</p>
1981
     */
1982
    public function isAlpha(): bool
1983
    {
1984
        return $this->utf8::is_alpha($this->str);
30✔
1985
    }
1986

1987
    /**
1988
     * Returns true if the string contains only alphabetic and numeric chars, false otherwise.
1989
     *
1990
     * EXAMPLE: <code>
1991
     * s('دانيال1')->isAlphanumeric(); // true
1992
     * </code>
1993
     *
1994
     * @psalm-mutation-free
1995
     *
1996
     * @return bool
1997
     *              <p>Whether or not $str contains only alphanumeric chars.</p>
1998
     */
1999
    public function isAlphanumeric(): bool
2000
    {
2001
        return $this->utf8::is_alphanumeric($this->str);
39✔
2002
    }
2003

2004
    /**
2005
     * Checks if a string is 7 bit ASCII.
2006
     *
2007
     * EXAMPLE: <code>s('白')->isAscii; // false</code>
2008
     *
2009
     * @psalm-mutation-free
2010
     *
2011
     * @return bool
2012
     *              <p>
2013
     *              <strong>true</strong> if it is ASCII<br>
2014
     *              <strong>false</strong> otherwise
2015
     *              </p>
2016
     *
2017
     * @noinspection GetSetMethodCorrectnessInspection
2018
     */
2019
    public function isAscii(): bool
2020
    {
2021
        return $this->utf8::is_ascii($this->str);
×
2022
    }
2023

2024
    /**
2025
     * Returns true if the string is base64 encoded, false otherwise.
2026
     *
2027
     * EXAMPLE: <code>
2028
     * s('Zm9vYmFy')->isBase64(); // true
2029
     * </code>
2030
     *
2031
     * @param bool $emptyStringIsValid
2032
     *
2033
     * @psalm-mutation-free
2034
     *
2035
     * @return bool
2036
     *              <p>Whether or not $str is base64 encoded.</p>
2037
     */
2038
    public function isBase64($emptyStringIsValid = true): bool
2039
    {
2040
        return $this->utf8::is_base64($this->str, $emptyStringIsValid);
21✔
2041
    }
2042

2043
    /**
2044
     * Check if the input is binary... (is look like a hack).
2045
     *
2046
     * EXAMPLE: <code>s(01)->isBinary(); // true</code>
2047
     *
2048
     * @psalm-mutation-free
2049
     *
2050
     * @return bool
2051
     */
2052
    public function isBinary(): bool
2053
    {
2054
        return $this->utf8::is_binary($this->str);
1✔
2055
    }
2056

2057
    /**
2058
     * Returns true if the string contains only whitespace chars, false otherwise.
2059
     *
2060
     * EXAMPLE: <code>
2061
     * s("\n\t  \v\f")->isBlank(); // true
2062
     * </code>
2063
     *
2064
     * @psalm-mutation-free
2065
     *
2066
     * @return bool
2067
     *              <p>Whether or not $str contains only whitespace characters.</p>
2068
     */
2069
    public function isBlank(): bool
2070
    {
2071
        return $this->utf8::is_blank($this->str);
45✔
2072
    }
2073

2074
    /**
2075
     * Checks if the given string is equal to any "Byte Order Mark".
2076
     *
2077
     * WARNING: Use "s::string_has_bom()" if you will check BOM in a string.
2078
     *
2079
     * EXAMPLE: <code>s->("\xef\xbb\xbf")->isBom(); // true</code>
2080
     *
2081
     * @psalm-mutation-free
2082
     *
2083
     * @return bool
2084
     *              <p><strong>true</strong> if the $utf8_chr is Byte Order Mark, <strong>false</strong> otherwise.</p>
2085
     */
2086
    public function isBom(): bool
2087
    {
2088
        return $this->utf8::is_bom($this->str);
×
2089
    }
2090

2091
    /**
2092
     * Returns true if the string contains a valid E-Mail address, false otherwise.
2093
     *
2094
     * EXAMPLE: <code>
2095
     * s('lars@moelleken.org')->isEmail(); // true
2096
     * </code>
2097
     *
2098
     * @param bool $useExampleDomainCheck   [optional] <p>Default: false</p>
2099
     * @param bool $useTypoInDomainCheck    [optional] <p>Default: false</p>
2100
     * @param bool $useTemporaryDomainCheck [optional] <p>Default: false</p>
2101
     * @param bool $useDnsCheck             [optional] <p>Default: false</p>
2102
     *
2103
     * @psalm-mutation-free
2104
     *
2105
     * @return bool
2106
     *              <p>Whether or not $str contains a valid E-Mail address.</p>
2107
     */
2108
    public function isEmail(
2109
        bool $useExampleDomainCheck = false,
2110
        bool $useTypoInDomainCheck = false,
2111
        bool $useTemporaryDomainCheck = false,
2112
        bool $useDnsCheck = false
2113
    ): bool {
2114
        /**
2115
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the email-check class
2116
         */
2117
        return EmailCheck::isValid($this->str, $useExampleDomainCheck, $useTypoInDomainCheck, $useTemporaryDomainCheck, $useDnsCheck);
2✔
2118
    }
2119

2120
    /**
2121
     * Determine whether the string is considered to be empty.
2122
     *
2123
     * A variable is considered empty if it does not exist or if its value equals FALSE.
2124
     *
2125
     * EXAMPLE: <code>
2126
     * s('')->isEmpty(); // true
2127
     * </code>
2128
     *
2129
     * @psalm-mutation-free
2130
     *
2131
     * @return bool
2132
     *              <p>Whether or not $str is empty().</p>
2133
     */
2134
    public function isEmpty(): bool
2135
    {
2136
        return $this->utf8::is_empty($this->str);
10✔
2137
    }
2138

2139
    /**
2140
     * Determine whether the string is equals to $str.
2141
     * Alias for isEqualsCaseSensitive()
2142
     *
2143
     * EXAMPLE: <code>
2144
     * s('foo')->isEquals('foo'); // true
2145
     * </code>
2146
     *
2147
     * @param string|Stringy ...$str
2148
     *
2149
     * @psalm-mutation-free
2150
     *
2151
     * @return bool
2152
     */
2153
    public function isEquals(...$str): bool
2154
    {
2155
        return $this->isEqualsCaseSensitive(...$str);
13✔
2156
    }
2157

2158
    /**
2159
     * Determine whether the string is equals to $str.
2160
     *
2161
     * EXAMPLE: <code>
2162
     * </code>
2163
     *
2164
     * @param float|int|string|Stringy ...$str <p>The string to compare.</p>
2165
     *
2166
     * @psalm-mutation-free
2167
     *
2168
     * @return bool
2169
     *              <p>Whether or not $str is equals.</p>
2170
     */
2171
    public function isEqualsCaseInsensitive(...$str): bool
2172
    {
2173
        $strUpper = $this->toUpperCase()->str;
3✔
2174

2175
        foreach ($str as $strTmp) {
3✔
2176
            /**
2177
             * @psalm-suppress RedundantConditionGivenDocblockType - wait for union-types :)
2178
             */
2179
            if ($strTmp instanceof self) {
3✔
2180
                if ($strUpper !== $strTmp->toUpperCase()->str) {
×
2181
                    return false;
×
2182
                }
2183
            } elseif (\is_scalar($strTmp)) {
3✔
2184
                if ($strUpper !== $this->utf8::strtoupper((string) $strTmp, $this->encoding)) {
3✔
2185
                    return false;
3✔
2186
                }
2187
            } else {
2188
                throw new \InvalidArgumentException('expected: int|float|string|Stringy -> given: ' . \print_r($strTmp, true) . ' [' . \gettype($strTmp) . ']');
×
2189
            }
2190
        }
2191

2192
        return true;
3✔
2193
    }
2194

2195
    /**
2196
     * Determine whether the string is equals to $str.
2197
     *
2198
     * EXAMPLE: <code>
2199
     * </code>
2200
     *
2201
     * @param float|int|string|Stringy ...$str <p>The string to compare.</p>
2202
     *
2203
     * @psalm-mutation-free
2204
     *
2205
     * @return bool
2206
     *              <p>Whether or not $str is equals.</p>
2207
     */
2208
    public function isEqualsCaseSensitive(...$str): bool
2209
    {
2210
        foreach ($str as $strTmp) {
14✔
2211
            /**
2212
             * @psalm-suppress RedundantConditionGivenDocblockType - wait for union-types :)
2213
             */
2214
            if ($strTmp instanceof self) {
14✔
2215
                if ($this->str !== $strTmp->str) {
2✔
2216
                    return false;
1✔
2217
                }
2218
            } elseif (\is_scalar($strTmp)) {
12✔
2219
                if ($this->str !== (string) $strTmp) {
12✔
2220
                    return false;
10✔
2221
                }
2222
            } else {
2223
                throw new \InvalidArgumentException('expected: int|float|string|Stringy -> given: ' . \print_r($strTmp, true) . ' [' . \gettype($strTmp) . ']');
×
2224
            }
2225
        }
2226

2227
        return true;
3✔
2228
    }
2229

2230
    /**
2231
     * Returns true if the string contains only hexadecimal chars, false otherwise.
2232
     *
2233
     * EXAMPLE: <code>
2234
     * s('A102F')->isHexadecimal(); // true
2235
     * </code>
2236
     *
2237
     * @psalm-mutation-free
2238
     *
2239
     * @return bool
2240
     *              <p>Whether or not $str contains only hexadecimal chars.</p>
2241
     */
2242
    public function isHexadecimal(): bool
2243
    {
2244
        return $this->utf8::is_hexadecimal($this->str);
39✔
2245
    }
2246

2247
    /**
2248
     * Returns true if the string contains HTML-Tags, false otherwise.
2249
     *
2250
     * EXAMPLE: <code>
2251
     * s('<h1>foo</h1>')->isHtml(); // true
2252
     * </code>
2253
     *
2254
     * @psalm-mutation-free
2255
     *
2256
     * @return bool
2257
     *              <p>Whether or not $str contains HTML-Tags.</p>
2258
     */
2259
    public function isHtml(): bool
2260
    {
2261
        return $this->utf8::is_html($this->str);
2✔
2262
    }
2263

2264
    /**
2265
     * Returns true if the string is JSON, false otherwise. Unlike json_decode
2266
     * in PHP 5.x, this method is consistent with PHP 7 and other JSON parsers,
2267
     * in that an empty string is not considered valid JSON.
2268
     *
2269
     * EXAMPLE: <code>
2270
     * s('{"foo":"bar"}')->isJson(); // true
2271
     * </code>
2272
     *
2273
     * @param bool $onlyArrayOrObjectResultsAreValid
2274
     *
2275
     * @psalm-mutation-free
2276
     *
2277
     * @return bool
2278
     *              <p>Whether or not $str is JSON.</p>
2279
     */
2280
    public function isJson($onlyArrayOrObjectResultsAreValid = false): bool
2281
    {
2282
        /**
2283
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to vendor stuff?
2284
         */
2285
        return $this->utf8::is_json(
60✔
2286
            $this->str,
60✔
2287
            $onlyArrayOrObjectResultsAreValid
60✔
2288
        );
60✔
2289
    }
2290

2291
    /**
2292
     * Returns true if the string contains only lower case chars, false otherwise.
2293
     *
2294
     * EXAMPLE: <code>
2295
     * s('fòôbàř')->isLowerCase(); // true
2296
     * </code>
2297
     *
2298
     * @psalm-mutation-free
2299
     *
2300
     * @return bool
2301
     *              <p>Whether or not $str contains only lower case characters.</p>
2302
     */
2303
    public function isLowerCase(): bool
2304
    {
2305
        return $this->utf8::is_lowercase($this->str);
24✔
2306
    }
2307

2308
    /**
2309
     * Determine whether the string is considered to be NOT empty.
2310
     *
2311
     * A variable is considered NOT empty if it does exist or if its value equals TRUE.
2312
     *
2313
     * EXAMPLE: <code>
2314
     * s('')->isNotEmpty(); // false
2315
     * </code>
2316
     *
2317
     * @psalm-mutation-free
2318
     *
2319
     * @return bool
2320
     *              <p>Whether or not $str is empty().</p>
2321
     */
2322
    public function isNotEmpty(): bool
2323
    {
2324
        return !$this->utf8::is_empty($this->str);
10✔
2325
    }
2326

2327
    /**
2328
     * Determine if the string is composed of numeric characters.
2329
     *
2330
     * EXAMPLE: <code>
2331
     * </code>
2332
     *
2333
     * @psalm-mutation-free
2334
     *
2335
     * @return bool
2336
     */
2337
    public function isNumeric(): bool
2338
    {
2339
        return \is_numeric($this->str);
4✔
2340
    }
2341

2342
    /**
2343
     * Determine if the string is composed of printable (non-invisible) characters.
2344
     *
2345
     * EXAMPLE: <code>
2346
     * </code>
2347
     *
2348
     * @psalm-mutation-free
2349
     *
2350
     * @return bool
2351
     */
2352
    public function isPrintable(): bool
2353
    {
2354
        return $this->utf8::is_printable($this->str);
3✔
2355
    }
2356

2357
    /**
2358
     * Determine if the string is composed of punctuation characters.
2359
     *
2360
     * EXAMPLE: <code>
2361
     * </code>
2362
     *
2363
     * @psalm-mutation-free
2364
     *
2365
     * @return bool
2366
     */
2367
    public function isPunctuation(): bool
2368
    {
2369
        return $this->utf8::is_punctuation($this->str);
3✔
2370
    }
2371

2372
    /**
2373
     * Returns true if the string is serialized, false otherwise.
2374
     *
2375
     * EXAMPLE: <code>
2376
     * s('a:1:{s:3:"foo";s:3:"bar";}')->isSerialized(); // true
2377
     * </code>
2378
     *
2379
     * @psalm-mutation-free
2380
     *
2381
     * @return bool
2382
     *              <p>Whether or not $str is serialized.</p>
2383
     */
2384
    public function isSerialized(): bool
2385
    {
2386
        return $this->utf8::is_serialized($this->str);
21✔
2387
    }
2388

2389
    /**
2390
     * Check if two strings are similar.
2391
     *
2392
     * EXAMPLE: <code>
2393
     * </code>
2394
     *
2395
     * @param string $str                     <p>The string to compare against.</p>
2396
     * @param float  $minPercentForSimilarity [optional] <p>The percentage of needed similarity. | Default: 80%</p>
2397
     *
2398
     * @psalm-mutation-free
2399
     *
2400
     * @return bool
2401
     */
2402
    public function isSimilar(string $str, float $minPercentForSimilarity = 80.0): bool
2403
    {
2404
        return $this->similarity($str) >= $minPercentForSimilarity;
2✔
2405
    }
2406

2407
    /**
2408
     * Returns true if the string contains only lower case chars, false
2409
     * otherwise.
2410
     *
2411
     * EXAMPLE: <code>
2412
     * s('FÒÔBÀŘ')->isUpperCase(); // true
2413
     * </code>
2414
     *
2415
     * @psalm-mutation-free
2416
     *
2417
     * @return bool
2418
     *              <p>Whether or not $str contains only lower case characters.</p>
2419
     */
2420
    public function isUpperCase(): bool
2421
    {
2422
        return $this->utf8::is_uppercase($this->str);
24✔
2423
    }
2424

2425
    /**
2426
     * /**
2427
     * Check if $url is an correct url.
2428
     *
2429
     * @param bool $disallow_localhost
2430
     *
2431
     * @psalm-mutation-free
2432
     *
2433
     * @return bool
2434
     */
2435
    public function isUrl(bool $disallow_localhost = false): bool
2436
    {
2437
        return $this->utf8::is_url($this->str, $disallow_localhost);
×
2438
    }
2439

2440
    /**
2441
     * Check if the string is UTF-16.
2442
     *
2443
     * @psalm-mutation-free
2444
     *
2445
     * @return false|int
2446
     *                   <strong>false</strong> if is't not UTF-16,<br>
2447
     *                   <strong>1</strong> for UTF-16LE,<br>
2448
     *                   <strong>2</strong> for UTF-16BE
2449
     */
2450
    public function isUtf16()
2451
    {
2452
        return $this->utf8::is_utf16($this->str);
×
2453
    }
2454

2455
    /**
2456
     * Check if the string is UTF-32.
2457
     *
2458
     * @psalm-mutation-free
2459
     *
2460
     * @return false|int
2461
     *                   <strong>false</strong> if is't not UTF-32,<br>
2462
     *                   <strong>1</strong> for UTF-32LE,<br>
2463
     *                   <strong>2</strong> for UTF-32BE
2464
     */
2465
    public function isUtf32()
2466
    {
2467
        return $this->utf8::is_utf32($this->str);
×
2468
    }
2469

2470
    /**
2471
     * Checks whether the passed input contains only byte sequences that appear valid UTF-8.
2472
     *
2473
     * EXAMPLE: <code>
2474
     * s('Iñtërnâtiônàlizætiøn')->isUtf8(); // true
2475
     * //
2476
     * s("Iñtërnâtiônàlizætiøn\xA0\xA1")->isUtf8(); // false
2477
     * </code>
2478
     *
2479
     * @param bool $strict <p>Check also if the string is not UTF-16 or UTF-32.</p>
2480
     *
2481
     * @psalm-mutation-free
2482
     *
2483
     * @return bool
2484
     */
2485
    public function isUtf8(bool $strict = false): bool
2486
    {
2487
        return $this->utf8::is_utf8($this->str, $strict);
×
2488
    }
2489

2490
    /**
2491
     * Returns true if the string contains only whitespace chars, false otherwise.
2492
     *
2493
     * EXAMPLE: <code>
2494
     * </code>
2495
     *
2496
     * @psalm-mutation-free
2497
     *
2498
     * @return bool
2499
     *              <p>Whether or not $str contains only whitespace characters.</p>
2500
     */
2501
    public function isWhitespace(): bool
2502
    {
2503
        return $this->isBlank();
30✔
2504
    }
2505

2506
    /**
2507
     * Returns value which can be serialized by json_encode().
2508
     *
2509
     * EXAMPLE: <code>
2510
     * </code>
2511
     *
2512
     * @psalm-mutation-free
2513
     *
2514
     * @return string The current value of the $str property
2515
     */
2516
    public function jsonSerialize(): mixed
2517
    {
2518
        return (string) $this;
2✔
2519
    }
2520

2521
    /**
2522
     * Convert the string to kebab-case.
2523
     *
2524
     * EXAMPLE: <code>
2525
     * </code>
2526
     *
2527
     * @psalm-mutation-free
2528
     *
2529
     * @return static
2530
     */
2531
    public function kebabCase(): self
2532
    {
2533
        $words = \array_map(
3✔
2534
            static function (self $word) {
3✔
2535
                return $word->toLowerCase();
3✔
2536
            },
3✔
2537
            $this->words('', true)
3✔
2538
        );
3✔
2539

2540
        return new static(\implode('-', $words), $this->encoding);
3✔
2541
    }
2542

2543
    /**
2544
     * Returns the last $n characters of the string.
2545
     *
2546
     * EXAMPLE: <code>
2547
     * s('fòôbàř')->last(3); // 'bàř'
2548
     * </code>
2549
     *
2550
     * @param int $n <p>Number of characters to retrieve from the end.</p>
2551
     *
2552
     * @psalm-mutation-free
2553
     *
2554
     * @return static
2555
     *                <p>Object with its $str being the last $n chars.</p>
2556
     */
2557
    public function last(int $n): self
2558
    {
2559
        return static::create(
36✔
2560
            $this->utf8::str_last_char(
36✔
2561
                $this->str,
36✔
2562
                $n,
36✔
2563
                $this->encoding
36✔
2564
            ),
36✔
2565
            $this->encoding
36✔
2566
        );
36✔
2567
    }
2568

2569
    /**
2570
     * Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".
2571
     * If no match is found returns new empty Stringy object.
2572
     *
2573
     * EXAMPLE: <code>
2574
     * </code>
2575
     *
2576
     * @param string $needle       <p>The string to look for.</p>
2577
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
2578
     *
2579
     * @psalm-mutation-free
2580
     *
2581
     * @return static
2582
     */
2583
    public function lastSubstringOf(string $needle, bool $beforeNeedle = false): self
2584
    {
2585
        return static::create(
4✔
2586
            $this->utf8::str_substr_last(
4✔
2587
                $this->str,
4✔
2588
                $needle,
4✔
2589
                $beforeNeedle,
4✔
2590
                $this->encoding
4✔
2591
            ),
4✔
2592
            $this->encoding
4✔
2593
        );
4✔
2594
    }
2595

2596
    /**
2597
     * Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".
2598
     * If no match is found returns new empty Stringy object.
2599
     *
2600
     * EXAMPLE: <code>
2601
     * </code>
2602
     *
2603
     * @param string $needle       <p>The string to look for.</p>
2604
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
2605
     *
2606
     * @psalm-mutation-free
2607
     *
2608
     * @return static
2609
     */
2610
    public function lastSubstringOfIgnoreCase(string $needle, bool $beforeNeedle = false): self
2611
    {
2612
        return static::create(
2✔
2613
            $this->utf8::str_isubstr_last(
2✔
2614
                $this->str,
2✔
2615
                $needle,
2✔
2616
                $beforeNeedle,
2✔
2617
                $this->encoding
2✔
2618
            ),
2✔
2619
            $this->encoding
2✔
2620
        );
2✔
2621
    }
2622

2623
    /**
2624
     * Returns the length of the string.
2625
     *
2626
     * EXAMPLE: <code>
2627
     * s('fòôbàř')->length(); // 6
2628
     * </code>
2629
     *
2630
     * @psalm-mutation-free
2631
     *
2632
     * @return int
2633
     *             <p>The number of characters in $str given the encoding.</p>
2634
     */
2635
    public function length(): int
2636
    {
2637
        return (int) $this->utf8::strlen($this->str, $this->encoding);
29✔
2638
    }
2639

2640
    /**
2641
     * Line-Wrap the string after $limit, but also after the next word.
2642
     *
2643
     * EXAMPLE: <code>
2644
     * </code>
2645
     *
2646
     * @param int         $limit           [optional] <p>The column width.</p>
2647
     * @param string      $break           [optional] <p>The line is broken using the optional break parameter.</p>
2648
     * @param bool        $add_final_break [optional] <p>
2649
     *                                     If this flag is true, then the method will add a $break at the end
2650
     *                                     of the result string.
2651
     *                                     </p>
2652
     * @param string|null $delimiter       [optional] <p>
2653
     *                                     You can change the default behavior, where we split the string by newline.
2654
     *                                     </p>
2655
     *
2656
     * @psalm-mutation-free
2657
     *
2658
     * @return static
2659
     */
2660
    public function lineWrap(
2661
        int $limit,
2662
        string $break = "\n",
2663
        bool $add_final_break = true,
2664
        ?string $delimiter = null
2665
    ): self {
2666
        if ($limit <= 0) {
5✔
2667
            return static::create('', $this->encoding);
1✔
2668
        }
2669

2670
        $delimiter = $delimiter === '' ? null : $delimiter;
4✔
2671

2672
        return static::create(
4✔
2673
            $this->utf8::wordwrap_per_line(
4✔
2674
                $this->str,
4✔
2675
                $limit,
4✔
2676
                $break,
4✔
2677
                true,
4✔
2678
                $add_final_break,
4✔
2679
                $delimiter
4✔
2680
            ),
4✔
2681
            $this->encoding
4✔
2682
        );
4✔
2683
    }
2684

2685
    /**
2686
     * Line-Wrap the string after $limit, but also after the next word.
2687
     *
2688
     * EXAMPLE: <code>
2689
     * </code>
2690
     *
2691
     * @param int         $limit           [optional] <p>The column width.</p>
2692
     * @param string      $break           [optional] <p>The line is broken using the optional break parameter.</p>
2693
     * @param bool        $add_final_break [optional] <p>
2694
     *                                     If this flag is true, then the method will add a $break at the end
2695
     *                                     of the result string.
2696
     *                                     </p>
2697
     * @param string|null $delimiter       [optional] <p>
2698
     *                                     You can change the default behavior, where we split the string by newline.
2699
     *                                     </p>
2700
     *
2701
     * @psalm-mutation-free
2702
     *
2703
     * @return static
2704
     */
2705
    public function lineWrapAfterWord(
2706
        int $limit,
2707
        string $break = "\n",
2708
        bool $add_final_break = true,
2709
        ?string $delimiter = null
2710
    ): self {
2711
        if ($limit <= 0) {
8✔
2712
            return static::create('', $this->encoding);
2✔
2713
        }
2714

2715
        $delimiter = $delimiter === '' ? null : $delimiter;
6✔
2716

2717
        return static::create(
6✔
2718
            $this->utf8::wordwrap_per_line(
6✔
2719
                $this->str,
6✔
2720
                $limit,
6✔
2721
                $break,
6✔
2722
                false,
6✔
2723
                $add_final_break,
6✔
2724
                $delimiter
6✔
2725
            ),
6✔
2726
            $this->encoding
6✔
2727
        );
6✔
2728
    }
2729

2730
    /**
2731
     * Splits on newlines and carriage returns, returning an array of Stringy
2732
     * objects corresponding to the lines in the string.
2733
     *
2734
     * EXAMPLE: <code>
2735
     * s("fòô\r\nbàř\n")->lines(); // ['fòô', 'bàř', '']
2736
     * </code>
2737
     *
2738
     * @psalm-mutation-free
2739
     *
2740
     * @return static[]
2741
     *                  <p>An array of Stringy objects.</p>
2742
     *
2743
     * @phpstan-return array<int,static>
2744
     */
2745
    public function lines(): array
2746
    {
2747
        if ($this->str === '') {
51✔
2748
            return [static::create('')];
3✔
2749
        }
2750

2751
        $strings = $this->utf8::str_to_lines($this->str);
48✔
2752
        /** @noinspection AlterInForeachInspection */
2753
        foreach ($strings as &$str) {
48✔
2754
            $str = static::create($str, $this->encoding);
48✔
2755
        }
2756

2757
        /** @noinspection PhpSillyAssignmentInspection */
2758
        /** @var static[] $strings */
2759
        $strings = $strings;
48✔
2760

2761
        return $strings;
48✔
2762
    }
2763

2764
    /**
2765
     * Splits on newlines and carriage returns, returning an array of Stringy
2766
     * objects corresponding to the lines in the string.
2767
     *
2768
     * EXAMPLE: <code>
2769
     * </code>
2770
     *
2771
     * @psalm-mutation-free
2772
     *
2773
     * @return CollectionStringy|static[]
2774
     *                                    <p>An collection of Stringy objects.</p>
2775
     *
2776
     * @phpstan-return CollectionStringy<int,static>
2777
     */
2778
    public function linesCollection(): CollectionStringy
2779
    {
2780
        /**
2781
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the collection class
2782
         */
2783
        return CollectionStringy::create(
34✔
2784
            $this->lines()
34✔
2785
        );
34✔
2786
    }
2787

2788
    /**
2789
     * Returns the longest common prefix between the string and $otherStr.
2790
     *
2791
     * EXAMPLE: <code>
2792
     * s('foobar')->longestCommonPrefix('foobaz'); // 'fooba'
2793
     * </code>
2794
     *
2795
     * @param string $otherStr <p>Second string for comparison.</p>
2796
     *
2797
     * @psalm-mutation-free
2798
     *
2799
     * @return static
2800
     *                <p>Object with its $str being the longest common prefix.</p>
2801
     */
2802
    public function longestCommonPrefix(string $otherStr): self
2803
    {
2804
        return static::create(
30✔
2805
            $this->utf8::str_longest_common_prefix(
30✔
2806
                $this->str,
30✔
2807
                $otherStr,
30✔
2808
                $this->encoding
30✔
2809
            ),
30✔
2810
            $this->encoding
30✔
2811
        );
30✔
2812
    }
2813

2814
    /**
2815
     * Returns the longest common substring between the string and $otherStr.
2816
     * In the case of ties, it returns that which occurs first.
2817
     *
2818
     * EXAMPLE: <code>
2819
     * s('foobar')->longestCommonSubstring('boofar'); // 'oo'
2820
     * </code>
2821
     *
2822
     * @param string $otherStr <p>Second string for comparison.</p>
2823
     *
2824
     * @psalm-mutation-free
2825
     *
2826
     * @return static
2827
     *                <p>Object with its $str being the longest common substring.</p>
2828
     */
2829
    public function longestCommonSubstring(string $otherStr): self
2830
    {
2831
        return static::create(
30✔
2832
            $this->utf8::str_longest_common_substring(
30✔
2833
                $this->str,
30✔
2834
                $otherStr,
30✔
2835
                $this->encoding
30✔
2836
            ),
30✔
2837
            $this->encoding
30✔
2838
        );
30✔
2839
    }
2840

2841
    /**
2842
     * Returns the longest common suffix between the string and $otherStr.
2843
     *
2844
     * EXAMPLE: <code>
2845
     * s('fòôbàř')->longestCommonSuffix('fòrbàř'); // 'bàř'
2846
     * </code>
2847
     *
2848
     * @param string $otherStr <p>Second string for comparison.</p>
2849
     *
2850
     * @psalm-mutation-free
2851
     *
2852
     * @return static
2853
     *                <p>Object with its $str being the longest common suffix.</p>
2854
     */
2855
    public function longestCommonSuffix(string $otherStr): self
2856
    {
2857
        return static::create(
30✔
2858
            $this->utf8::str_longest_common_suffix(
30✔
2859
                $this->str,
30✔
2860
                $otherStr,
30✔
2861
                $this->encoding
30✔
2862
            ),
30✔
2863
            $this->encoding
30✔
2864
        );
30✔
2865
    }
2866

2867
    /**
2868
     * Converts the first character of the string to lower case.
2869
     *
2870
     * EXAMPLE: <code>
2871
     * s('Σ Foo')->lowerCaseFirst(); // 'σ Foo'
2872
     * </code>
2873
     *
2874
     * @psalm-mutation-free
2875
     *
2876
     * @return static
2877
     *                <p>Object with the first character of $str being lower case.</p>
2878
     */
2879
    public function lowerCaseFirst(): self
2880
    {
2881
        return static::create(
16✔
2882
            $this->utf8::lcfirst($this->str, $this->encoding),
16✔
2883
            $this->encoding
16✔
2884
        );
16✔
2885
    }
2886

2887
    /**
2888
     * Determine if the string matches another string regardless of case.
2889
     * Alias for isEqualsCaseInsensitive()
2890
     *
2891
     * EXAMPLE: <code>
2892
     * </code>
2893
     *
2894
     * @psalm-mutation-free
2895
     *
2896
     * @param string|Stringy ...$str
2897
     *                               <p>The string to compare against.</p>
2898
     *
2899
     * @psalm-mutation-free
2900
     *
2901
     * @return bool
2902
     */
2903
    public function matchCaseInsensitive(...$str): bool
2904
    {
2905
        return $this->isEqualsCaseInsensitive(...$str);
3✔
2906
    }
2907

2908
    /**
2909
     * Determine if the string matches another string.
2910
     * Alias for isEqualsCaseSensitive()
2911
     *
2912
     * EXAMPLE: <code>
2913
     * </code>
2914
     *
2915
     * @psalm-mutation-free
2916
     *
2917
     * @param string|Stringy ...$str
2918
     *                               <p>The string to compare against.</p>
2919
     *
2920
     * @psalm-mutation-free
2921
     *
2922
     * @return bool
2923
     */
2924
    public function matchCaseSensitive(...$str): bool
2925
    {
2926
        return $this->isEqualsCaseSensitive(...$str);
7✔
2927
    }
2928

2929
    /**
2930
     * Create a md5 hash from the current string.
2931
     *
2932
     * @psalm-mutation-free
2933
     *
2934
     * @return static
2935
     */
2936
    public function md5(): self
2937
    {
2938
        return static::create($this->hash('md5'), $this->encoding);
2✔
2939
    }
2940

2941
    /**
2942
     * Replace all breaks [<br> | \r\n | \r | \n | ...] into "<br>".
2943
     *
2944
     * EXAMPLE: <code>
2945
     * </code>
2946
     *
2947
     * @return static
2948
     */
2949
    public function newLineToHtmlBreak(): self
2950
    {
2951
        return $this->removeHtmlBreak('<br>');
1✔
2952
    }
2953

2954
    /**
2955
     * Get every nth character of the string.
2956
     *
2957
     * EXAMPLE: <code>
2958
     * </code>
2959
     *
2960
     * @param int $step   <p>The number of characters to step.</p>
2961
     * @param int $offset [optional] <p>The string offset to start at.</p>
2962
     *
2963
     * @psalm-mutation-free
2964
     *
2965
     * @return static
2966
     */
2967
    public function nth(int $step, int $offset = 0): self
2968
    {
2969
        $length = $step - 1;
4✔
2970
        $substring = $this->substr($offset)->toString();
4✔
2971

2972
        if ($substring === '') {
4✔
2973
            return new static('', $this->encoding);
×
2974
        }
2975

2976
        \preg_match_all(
4✔
2977
            "/(?:^|(?:.|\p{L}|\w){" . $length . "})(.|\p{L}|\w)/u",
4✔
2978
            $substring,
4✔
2979
            $matches
4✔
2980
        );
4✔
2981

2982
        return new static(\implode('', $matches[1] ?? []), $this->encoding);
4✔
2983
    }
2984

2985
    /**
2986
     * Returns the integer value of the current string.
2987
     *
2988
     * EXAMPLE: <code>
2989
     * s('foo1 ba2r')->extractIntegers(); // '12'
2990
     * </code>
2991
     *
2992
     * @psalm-mutation-free
2993
     *
2994
     * @return static
2995
     */
2996
    public function extractIntegers(): self
2997
    {
2998
        if ($this->str === '') {
1✔
2999
            return new static('', $this->encoding);
1✔
3000
        }
3001

3002
        \preg_match_all('/(?<integers>\d+)/', $this->str, $matches);
1✔
3003

3004
        return static::create(
1✔
3005
            \implode('', $matches['integers']),
1✔
3006
            $this->encoding
1✔
3007
        );
1✔
3008
    }
3009

3010
    /**
3011
     * Returns the special chars of the current string.
3012
     *
3013
     * EXAMPLE: <code>
3014
     * s('foo1 ba2!r')->extractSpecialCharacters(); // '!'
3015
     * </code>
3016
     *
3017
     * @psalm-mutation-free
3018
     *
3019
     * @return static
3020
     */
3021
    public function extractSpecialCharacters(): self
3022
    {
3023
        if ($this->str === '') {
1✔
3024
            return new static('', $this->encoding);
1✔
3025
        }
3026

3027
        // no letter, no digit, no space
3028
        \preg_match_all('/((?![\p{L}0-9\s]+).)/u', $this->str, $matches);
1✔
3029

3030
        return static::create(
1✔
3031
            \implode('', $matches[0]),
1✔
3032
            $this->encoding
1✔
3033
        );
1✔
3034
    }
3035

3036
    /**
3037
     * Returns whether or not a character exists at an index. Offsets may be
3038
     * negative to count from the last character in the string. Implements
3039
     * part of the ArrayAccess interface.
3040
     *
3041
     * EXAMPLE: <code>
3042
     * </code>
3043
     *
3044
     * @param int $offset <p>The index to check.</p>
3045
     *
3046
     * @psalm-mutation-free
3047
     *
3048
     * @return bool
3049
     *              <p>Whether or not the index exists.</p>
3050
     */
3051
    public function offsetExists($offset): bool
3052
    {
3053
        return $this->utf8::str_offset_exists(
18✔
3054
            $this->str,
18✔
3055
            $offset,
18✔
3056
            $this->encoding
18✔
3057
        );
18✔
3058
    }
3059

3060
    /**
3061
     * Returns the character at the given index. Offsets may be negative to
3062
     * count from the last character in the string. Implements part of the
3063
     * ArrayAccess interface, and throws an OutOfBoundsException if the index
3064
     * does not exist.
3065
     *
3066
     * EXAMPLE: <code>
3067
     * </code>
3068
     *
3069
     * @param int $offset <p>The <strong>index</strong> from which to retrieve the char.</p>
3070
     *
3071
     * @throws \OutOfBoundsException
3072
     *                               <p>If the positive or negative offset does not exist.</p>
3073
     *
3074
     * @return string
3075
     *                <p>The character at the specified index.</p>
3076
     *
3077
     * @psalm-mutation-free
3078
     */
3079
    public function offsetGet($offset): string
3080
    {
3081
        $length = $this->length();
10✔
3082

3083
        if (
3084
            ($offset >= 0 && $length <= $offset)
10✔
3085
            ||
3086
            $length < \abs($offset)
10✔
3087
        ) {
3088
            throw new \OutOfBoundsException('No character exists at the index');
5✔
3089
        }
3090

3091
        if ($this->encoding === 'UTF-8') {
5✔
3092
            return (string) \mb_substr($this->str, $offset, 1);
5✔
3093
        }
3094

3095
        return (string) $this->utf8::substr($this->str, $offset, 1, $this->encoding);
×
3096
    }
3097

3098
    /**
3099
     * Implements part of the ArrayAccess interface, but throws an exception
3100
     * when called. This maintains the immutability of Stringy objects.
3101
     *
3102
     * EXAMPLE: <code>
3103
     * </code>
3104
     *
3105
     * @param int   $offset <p>The index of the character.</p>
3106
     * @param mixed $value  <p>Value to set.</p>
3107
     *
3108
     * @throws \Exception
3109
     *                    <p>When called.</p>
3110
     *
3111
     * @return void
3112
     */
3113
    public function offsetSet($offset, $value): void
3114
    {
3115
        // Stringy is immutable, cannot directly set char
3116
        throw new \Exception('Stringy object is immutable, cannot modify char');
3✔
3117
    }
3118

3119
    /**
3120
     * Implements part of the ArrayAccess interface, but throws an exception
3121
     * when called. This maintains the immutability of Stringy objects.
3122
     *
3123
     * EXAMPLE: <code>
3124
     * </code>
3125
     *
3126
     * @param int $offset <p>The index of the character.</p>
3127
     *
3128
     * @throws \Exception
3129
     *                    <p>When called.</p>
3130
     *
3131
     * @return void
3132
     */
3133
    public function offsetUnset($offset): void
3134
    {
3135
        // Don't allow directly modifying the string
3136
        throw new \Exception('Stringy object is immutable, cannot unset char');
3✔
3137
    }
3138

3139
    /**
3140
     * Pads the string to a given length with $padStr. If length is less than
3141
     * or equal to the length of the string, no padding takes places. The
3142
     * default string used for padding is a space, and the default type (one of
3143
     * 'left', 'right', 'both') is 'right'. Throws an InvalidArgumentException
3144
     * if $padType isn't one of those 3 values.
3145
     *
3146
     * EXAMPLE: <code>
3147
     * s('fòôbàř')->pad(9, '-/', 'left'); // '-/-fòôbàř'
3148
     * </code>
3149
     *
3150
     * @param int    $length  <p>Desired string length after padding.</p>
3151
     * @param string $padStr  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
3152
     * @param string $padType [optional] <p>One of 'left', 'right', 'both'. Default: 'right'</p>
3153
     *
3154
     * @throws \InvalidArgumentException
3155
     *                                   <p>If $padType isn't one of 'right', 'left' or 'both'.</p>
3156
     *
3157
     * @return static
3158
     *                <p>Object with a padded $str.</p>
3159
     *
3160
     * @psalm-mutation-free
3161
     */
3162
    public function pad(int $length, string $padStr = ' ', string $padType = 'right'): self
3163
    {
3164
        return static::create(
39✔
3165
            $this->utf8::str_pad(
39✔
3166
                $this->str,
39✔
3167
                $length,
39✔
3168
                $padStr,
39✔
3169
                $padType,
39✔
3170
                $this->encoding
39✔
3171
            )
39✔
3172
        );
39✔
3173
    }
3174

3175
    /**
3176
     * Returns a new string of a given length such that both sides of the
3177
     * string are padded. Alias for pad() with a $padType of 'both'.
3178
     *
3179
     * EXAMPLE: <code>
3180
     * s('foo bar')->padBoth(9, ' '); // ' foo bar '
3181
     * </code>
3182
     *
3183
     * @param int    $length <p>Desired string length after padding.</p>
3184
     * @param string $padStr [optional] <p>String used to pad, defaults to space. Default: ' '</p>
3185
     *
3186
     * @psalm-mutation-free
3187
     *
3188
     * @return static
3189
     *                <p>String with padding applied.</p>
3190
     */
3191
    public function padBoth(int $length, string $padStr = ' '): self
3192
    {
3193
        return static::create(
33✔
3194
            $this->utf8::str_pad_both(
33✔
3195
                $this->str,
33✔
3196
                $length,
33✔
3197
                $padStr,
33✔
3198
                $this->encoding
33✔
3199
            )
33✔
3200
        );
33✔
3201
    }
3202

3203
    /**
3204
     * Returns a new string of a given length such that the beginning of the
3205
     * string is padded. Alias for pad() with a $padType of 'left'.
3206
     *
3207
     * EXAMPLE: <code>
3208
     * s('foo bar')->padLeft(9, ' '); // '  foo bar'
3209
     * </code>
3210
     *
3211
     * @param int    $length <p>Desired string length after padding.</p>
3212
     * @param string $padStr [optional] <p>String used to pad, defaults to space. Default: ' '</p>
3213
     *
3214
     * @psalm-mutation-free
3215
     *
3216
     * @return static
3217
     *                <p>String with left padding.</p>
3218
     */
3219
    public function padLeft(int $length, string $padStr = ' '): self
3220
    {
3221
        return static::create(
21✔
3222
            $this->utf8::str_pad_left(
21✔
3223
                $this->str,
21✔
3224
                $length,
21✔
3225
                $padStr,
21✔
3226
                $this->encoding
21✔
3227
            )
21✔
3228
        );
21✔
3229
    }
3230

3231
    /**
3232
     * Returns a new string of a given length such that the end of the string
3233
     * is padded. Alias for pad() with a $padType of 'right'.
3234
     *
3235
     * EXAMPLE: <code>
3236
     * s('foo bar')->padRight(10, '_*'); // 'foo bar_*_'
3237
     * </code>
3238
     *
3239
     * @param int    $length <p>Desired string length after padding.</p>
3240
     * @param string $padStr [optional] <p>String used to pad, defaults to space. Default: ' '</p>
3241
     *
3242
     * @psalm-mutation-free
3243
     *
3244
     * @return static
3245
     *                <p>String with right padding.</p>
3246
     */
3247
    public function padRight(int $length, string $padStr = ' '): self
3248
    {
3249
        return static::create(
21✔
3250
            $this->utf8::str_pad_right(
21✔
3251
                $this->str,
21✔
3252
                $length,
21✔
3253
                $padStr,
21✔
3254
                $this->encoding
21✔
3255
            )
21✔
3256
        );
21✔
3257
    }
3258

3259
    /**
3260
     * Convert the string to PascalCase.
3261
     * Alias for studlyCase()
3262
     *
3263
     * EXAMPLE: <code>
3264
     * </code>
3265
     *
3266
     * @psalm-mutation-free
3267
     *
3268
     * @return static
3269
     */
3270
    public function pascalCase(): self
3271
    {
3272
        return $this->studlyCase();
3✔
3273
    }
3274

3275
    /**
3276
     * Returns a new string starting with $prefix.
3277
     *
3278
     * EXAMPLE: <code>
3279
     * s('bàř')->prepend('fòô'); // 'fòôbàř'
3280
     * </code>
3281
     *
3282
     * @param string ...$prefix <p>The string to append.</p>
3283
     *
3284
     * @psalm-mutation-free
3285
     *
3286
     * @return static
3287
     *                <p>Object with appended $prefix.</p>
3288
     */
3289
    public function prepend(string ...$prefix): self
3290
    {
3291
        if (\count($prefix) <= 1) {
8✔
3292
            $prefix = $prefix[0];
6✔
3293
        } else {
3294
            $prefix = \implode('', $prefix);
2✔
3295
        }
3296

3297
        return static::create($prefix . $this->str, $this->encoding);
8✔
3298
    }
3299

3300
    /**
3301
     * Returns a new string starting with $prefix.
3302
     *
3303
     * EXAMPLE: <code>
3304
     * </code>
3305
     *
3306
     * @param CollectionStringy|static ...$prefix <p>The Stringy objects to append.</p>
3307
     *
3308
     * @phpstan-param CollectionStringy<int,static>|static ...$prefix
3309
     *
3310
     * @psalm-mutation-free
3311
     *
3312
     * @return static
3313
     *                <p>Object with appended $prefix.</p>
3314
     */
3315
    public function prependStringy(...$prefix): self
3316
    {
3317
        $prefixStr = '';
1✔
3318
        foreach ($prefix as $prefixTmp) {
1✔
3319
            if ($prefixTmp instanceof CollectionStringy) {
1✔
3320
                $prefixStr .= $prefixTmp->implode('');
1✔
3321
            } else {
3322
                $prefixStr .= $prefixTmp->toString();
1✔
3323
            }
3324
        }
3325

3326
        return static::create($prefixStr . $this->str, $this->encoding);
1✔
3327
    }
3328

3329
    /**
3330
     * Replaces all occurrences of $pattern in $str by $replacement.
3331
     *
3332
     * EXAMPLE: <code>
3333
     * s('fòô ')->regexReplace('f[òô]+\s', 'bàř'); // 'bàř'
3334
     * s('fò')->regexReplace('(ò)', '\\1ô'); // 'fòô'
3335
     * </code>
3336
     *
3337
     * @param string $pattern     <p>The regular expression pattern.</p>
3338
     * @param string $replacement <p>The string to replace with.</p>
3339
     * @param string $options     [optional] <p>Matching conditions to be used.</p>
3340
     * @param string $delimiter   [optional] <p>Delimiter the the regex. Default: '/'</p>
3341
     *
3342
     * @psalm-mutation-free
3343
     *
3344
     * @return static
3345
     *                <p>Object with the result2ing $str after the replacements.</p>
3346
     */
3347
    public function regexReplace(
3348
        string $pattern,
3349
        string $replacement,
3350
        string $options = '',
3351
        string $delimiter = '/'
3352
    ): self {
3353
        return static::create(
29✔
3354
            $this->utf8::regex_replace(
29✔
3355
                $this->str,
29✔
3356
                $pattern,
29✔
3357
                $replacement,
29✔
3358
                $options,
29✔
3359
                $delimiter
29✔
3360
            ),
29✔
3361
            $this->encoding
29✔
3362
        );
29✔
3363
    }
3364

3365
    /**
3366
     * Remove html via "strip_tags()" from the string.
3367
     *
3368
     * EXAMPLE: <code>
3369
     * s('řàb <ô>òf\', ô<br/>foo <a href="#">lall</a>')->removeHtml('<br><br/>'); // 'řàb òf\', ô<br/>foo lall'
3370
     * </code>
3371
     *
3372
     * @param string $allowableTags [optional] <p>You can use the optional second parameter to specify tags which should
3373
     *                              not be stripped. Default: null
3374
     *                              </p>
3375
     *
3376
     * @psalm-mutation-free
3377
     *
3378
     * @return static
3379
     */
3380
    public function removeHtml(string $allowableTags = ''): self
3381
    {
3382
        return static::create(
12✔
3383
            $this->utf8::remove_html($this->str, $allowableTags),
12✔
3384
            $this->encoding
12✔
3385
        );
12✔
3386
    }
3387

3388
    /**
3389
     * Remove all breaks [<br> | \r\n | \r | \n | ...] from the string.
3390
     *
3391
     * EXAMPLE: <code>
3392
     * s('řàb <ô>òf\', ô<br/>foo <a href="#">lall</a>')->removeHtmlBreak(''); // 'řàb <ô>òf\', ô< foo <a href="#">lall</a>'
3393
     * </code>
3394
     *
3395
     * @param string $replacement [optional] <p>Default is a empty string.</p>
3396
     *
3397
     * @psalm-mutation-free
3398
     *
3399
     * @return static
3400
     */
3401
    public function removeHtmlBreak(string $replacement = ''): self
3402
    {
3403
        return static::create(
13✔
3404
            $this->utf8::remove_html_breaks($this->str, $replacement),
13✔
3405
            $this->encoding
13✔
3406
        );
13✔
3407
    }
3408

3409
    /**
3410
     * Returns a new string with the prefix $substring removed, if present.
3411
     *
3412
     * EXAMPLE: <code>
3413
     * s('fòôbàř')->removeLeft('fòô'); // 'bàř'
3414
     * </code>
3415
     *
3416
     * @param string $substring <p>The prefix to remove.</p>
3417
     *
3418
     * @psalm-mutation-free
3419
     *
3420
     * @return static
3421
     *                <p>Object having a $str without the prefix $substring.</p>
3422
     */
3423
    public function removeLeft(string $substring): self
3424
    {
3425
        return static::create(
36✔
3426
            $this->utf8::remove_left($this->str, $substring, $this->encoding),
36✔
3427
            $this->encoding
36✔
3428
        );
36✔
3429
    }
3430

3431
    /**
3432
     * Returns a new string with the suffix $substring removed, if present.
3433
     *
3434
     * EXAMPLE: <code>
3435
     * s('fòôbàř')->removeRight('bàř'); // 'fòô'
3436
     * </code>
3437
     *
3438
     * @param string $substring <p>The suffix to remove.</p>
3439
     *
3440
     * @psalm-mutation-free
3441
     *
3442
     * @return static
3443
     *                <p>Object having a $str without the suffix $substring.</p>
3444
     */
3445
    public function removeRight(string $substring): self
3446
    {
3447
        return static::create(
36✔
3448
            $this->utf8::remove_right($this->str, $substring, $this->encoding),
36✔
3449
            $this->encoding
36✔
3450
        );
36✔
3451
    }
3452

3453
    /**
3454
     * Try to remove all XSS-attacks from the string.
3455
     *
3456
     * EXAMPLE: <code>
3457
     * s('<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>')->removeXss(); // '<IMG >'
3458
     * </code>
3459
     *
3460
     * @psalm-mutation-free
3461
     *
3462
     * @return static
3463
     */
3464
    public function removeXss(): self
3465
    {
3466
        /**
3467
         * @var AntiXSS|null
3468
         *
3469
         * @psalm-suppress ImpureStaticVariable
3470
         */
3471
        static $antiXss = null;
12✔
3472

3473
        if ($antiXss === null) {
12✔
3474
            $antiXss = new AntiXSS();
1✔
3475
        }
3476

3477
        /**
3478
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the anti-xss class
3479
         */
3480
        $str = $antiXss->xss_clean($this->str);
12✔
3481

3482
        return static::create($str, $this->encoding);
12✔
3483
    }
3484

3485
    /**
3486
     * Returns a repeated string given a multiplier.
3487
     *
3488
     * EXAMPLE: <code>
3489
     * s('α')->repeat(3); // 'ααα'
3490
     * </code>
3491
     *
3492
     * @param int $multiplier <p>The number of times to repeat the string.</p>
3493
     *
3494
     * @psalm-mutation-free
3495
     *
3496
     * @return static
3497
     *                <p>Object with a repeated str.</p>
3498
     */
3499
    public function repeat(int $multiplier): self
3500
    {
3501
        return static::create(
21✔
3502
            \str_repeat($this->str, $multiplier),
21✔
3503
            $this->encoding
21✔
3504
        );
21✔
3505
    }
3506

3507
    /**
3508
     * Replaces all occurrences of $search in $str by $replacement.
3509
     *
3510
     * EXAMPLE: <code>
3511
     * s('fòô bàř fòô bàř')->replace('fòô ', ''); // 'bàř bàř'
3512
     * </code>
3513
     *
3514
     * @param string $search        <p>The needle to search for.</p>
3515
     * @param string $replacement   <p>The string to replace with.</p>
3516
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
3517
     *
3518
     * @psalm-mutation-free
3519
     *
3520
     * @return static
3521
     *                <p>Object with the resulting $str after the replacements.</p>
3522
     */
3523
    public function replace(string $search, string $replacement, bool $caseSensitive = true): self
3524
    {
3525
        if ($search === '' && $replacement === '') {
76✔
3526
            return static::create($this->str, $this->encoding);
16✔
3527
        }
3528

3529
        if ($this->str === '' && $search === '') {
60✔
3530
            return static::create($replacement, $this->encoding);
2✔
3531
        }
3532

3533
        if ($caseSensitive) {
58✔
3534
            return static::create(
48✔
3535
                \str_replace($search, $replacement, $this->str),
48✔
3536
                $this->encoding
48✔
3537
            );
48✔
3538
        }
3539

3540
        return static::create(
10✔
3541
            $this->utf8::str_ireplace($search, $replacement, $this->str),
10✔
3542
            $this->encoding
10✔
3543
        );
10✔
3544
    }
3545

3546
    /**
3547
     * Replaces all occurrences of $search in $str by $replacement.
3548
     *
3549
     * EXAMPLE: <code>
3550
     * s('fòô bàř lall bàř')->replaceAll(['fòÔ ', 'lall'], '', false); // 'bàř bàř'
3551
     * </code>
3552
     *
3553
     * @param string[]        $search        <p>The elements to search for.</p>
3554
     * @param string|string[] $replacement   <p>The string to replace with.</p>
3555
     * @param bool            $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
3556
     *
3557
     * @psalm-mutation-free
3558
     *
3559
     * @return static
3560
     *                <p>Object with the resulting $str after the replacements.</p>
3561
     */
3562
    public function replaceAll(array $search, $replacement, bool $caseSensitive = true): self
3563
    {
3564
        if ($caseSensitive) {
61✔
3565
            return static::create(
47✔
3566
                \str_replace($search, $replacement, $this->str),
47✔
3567
                $this->encoding
47✔
3568
            );
47✔
3569
        }
3570

3571
        return static::create(
14✔
3572
            $this->utf8::str_ireplace($search, $replacement, $this->str),
14✔
3573
            $this->encoding
14✔
3574
        );
14✔
3575
    }
3576

3577
    /**
3578
     * Replaces all occurrences of $search from the beginning of string with $replacement.
3579
     *
3580
     * EXAMPLE: <code>
3581
     * s('fòô bàř fòô bàř')->replaceBeginning('fòô', ''); // ' bàř bàř'
3582
     * </code>
3583
     *
3584
     * @param string $search      <p>The string to search for.</p>
3585
     * @param string $replacement <p>The replacement.</p>
3586
     *
3587
     * @psalm-mutation-free
3588
     *
3589
     * @return static
3590
     *                <p>Object with the resulting $str after the replacements.</p>
3591
     */
3592
    public function replaceBeginning(string $search, string $replacement): self
3593
    {
3594
        return static::create(
32✔
3595
            $this->utf8::str_replace_beginning($this->str, $search, $replacement),
32✔
3596
            $this->encoding
32✔
3597
        );
32✔
3598
    }
3599

3600
    /**
3601
     * Replaces all occurrences of $search from the ending of string with $replacement.
3602
     *
3603
     * EXAMPLE: <code>
3604
     * s('fòô bàř fòô bàř')->replaceEnding('bàř', ''); // 'fòô bàř fòô '
3605
     * </code>
3606
     *
3607
     * @param string $search      <p>The string to search for.</p>
3608
     * @param string $replacement <p>The replacement.</p>
3609
     *
3610
     * @psalm-mutation-free
3611
     *
3612
     * @return static
3613
     *                <p>Object with the resulting $str after the replacements.</p>
3614
     */
3615
    public function replaceEnding(string $search, string $replacement): self
3616
    {
3617
        return static::create(
32✔
3618
            $this->utf8::str_replace_ending($this->str, $search, $replacement),
32✔
3619
            $this->encoding
32✔
3620
        );
32✔
3621
    }
3622

3623
    /**
3624
     * Replaces first occurrences of $search from the beginning of string with $replacement.
3625
     *
3626
     * EXAMPLE: <code>
3627
     * </code>
3628
     *
3629
     * @param string $search      <p>The string to search for.</p>
3630
     * @param string $replacement <p>The replacement.</p>
3631
     *
3632
     * @psalm-mutation-free
3633
     *
3634
     * @return static
3635
     *                <p>Object with the resulting $str after the replacements.</p>
3636
     */
3637
    public function replaceFirst(string $search, string $replacement): self
3638
    {
3639
        return static::create(
32✔
3640
            $this->utf8::str_replace_first($search, $replacement, $this->str),
32✔
3641
            $this->encoding
32✔
3642
        );
32✔
3643
    }
3644

3645
    /**
3646
     * Replaces last occurrences of $search from the ending of string with $replacement.
3647
     *
3648
     * EXAMPLE: <code>
3649
     * </code>
3650
     *
3651
     * @param string $search      <p>The string to search for.</p>
3652
     * @param string $replacement <p>The replacement.</p>
3653
     *
3654
     * @psalm-mutation-free
3655
     *
3656
     * @return static
3657
     *                <p>Object with the resulting $str after the replacements.</p>
3658
     */
3659
    public function replaceLast(string $search, string $replacement): self
3660
    {
3661
        return static::create(
30✔
3662
            $this->utf8::str_replace_last($search, $replacement, $this->str),
30✔
3663
            $this->encoding
30✔
3664
        );
30✔
3665
    }
3666

3667
    /**
3668
     * Returns a reversed string. A multibyte version of strrev().
3669
     *
3670
     * EXAMPLE: <code>
3671
     * s('fòôbàř')->reverse(); // 'řàbôòf'
3672
     * </code>
3673
     *
3674
     * @psalm-mutation-free
3675
     *
3676
     * @return static
3677
     *                <p>Object with a reversed $str.</p>
3678
     */
3679
    public function reverse(): self
3680
    {
3681
        return static::create($this->utf8::strrev($this->str), $this->encoding);
15✔
3682
    }
3683

3684
    /**
3685
     * Truncates the string to a given length, while ensuring that it does not
3686
     * split words. If $substring is provided, and truncating occurs, the
3687
     * string is further truncated so that the substring may be appended without
3688
     * exceeding the desired length.
3689
     *
3690
     * EXAMPLE: <code>
3691
     * s('What are your plans today?')->safeTruncate(22, '...'); // 'What are your plans...'
3692
     * </code>
3693
     *
3694
     * @param int    $length                          <p>Desired length of the truncated string.</p>
3695
     * @param string $substring                       [optional] <p>The substring to append if it can fit. Default: ''</p>
3696
     * @param bool   $ignoreDoNotSplitWordsForOneWord
3697
     *
3698
     * @psalm-mutation-free
3699
     *
3700
     * @return static
3701
     *                <p>Object with the resulting $str after truncating.</p>
3702
     */
3703
    public function safeTruncate(
3704
        int $length,
3705
        string $substring = '',
3706
        bool $ignoreDoNotSplitWordsForOneWord = true
3707
    ): self {
3708
        return static::create(
68✔
3709
            $this->utf8::str_truncate_safe(
68✔
3710
                $this->str,
68✔
3711
                $length,
68✔
3712
                $substring,
68✔
3713
                $this->encoding,
68✔
3714
                $ignoreDoNotSplitWordsForOneWord
68✔
3715
            ),
68✔
3716
            $this->encoding
68✔
3717
        );
68✔
3718
    }
3719

3720
    /**
3721
     * Set the internal character encoding.
3722
     *
3723
     * EXAMPLE: <code>
3724
     * </code>
3725
     *
3726
     * @param string $new_encoding <p>The desired character encoding.</p>
3727
     *
3728
     * @psalm-mutation-free
3729
     *
3730
     * @return static
3731
     */
3732
    public function setInternalEncoding(string $new_encoding): self
3733
    {
3734
        return new static($this->str, $new_encoding);
1✔
3735
    }
3736

3737
    /**
3738
     * Create a sha1 hash from the current string.
3739
     *
3740
     * EXAMPLE: <code>
3741
     * </code>
3742
     *
3743
     * @psalm-mutation-free
3744
     *
3745
     * @return static
3746
     */
3747
    public function sha1(): self
3748
    {
3749
        return static::create($this->hash('sha1'), $this->encoding);
2✔
3750
    }
3751

3752
    /**
3753
     * Create a sha256 hash from the current string.
3754
     *
3755
     * EXAMPLE: <code>
3756
     * </code>
3757
     *
3758
     * @psalm-mutation-free
3759
     *
3760
     * @return static
3761
     */
3762
    public function sha256(): self
3763
    {
3764
        return static::create($this->hash('sha256'), $this->encoding);
2✔
3765
    }
3766

3767
    /**
3768
     * Create a sha512 hash from the current string.
3769
     *
3770
     * EXAMPLE: <code>
3771
     * </code>
3772
     *
3773
     * @psalm-mutation-free
3774
     *
3775
     * @return static
3776
     */
3777
    public function sha512(): self
3778
    {
3779
        return static::create($this->hash('sha512'), $this->encoding);
2✔
3780
    }
3781

3782
    /**
3783
     * Shorten the string after $length, but also after the next word.
3784
     *
3785
     * EXAMPLE: <code>
3786
     * s('this is a test')->shortenAfterWord(2, '...'); // 'this...'
3787
     * </code>
3788
     *
3789
     * @param int    $length   <p>The given length.</p>
3790
     * @param string $strAddOn [optional] <p>Default: '…'</p>
3791
     *
3792
     * @psalm-mutation-free
3793
     *
3794
     * @return static
3795
     */
3796
    public function shortenAfterWord(int $length, string $strAddOn = '…'): self
3797
    {
3798
        if ($length <= 0) {
12✔
3799
            return static::create('', $this->encoding);
4✔
3800
        }
3801

3802
        return static::create(
8✔
3803
            $this->utf8::str_limit_after_word($this->str, $length, $strAddOn),
8✔
3804
            $this->encoding
8✔
3805
        );
8✔
3806
    }
3807

3808
    /**
3809
     * A multibyte string shuffle function. It returns a string with its
3810
     * characters in random order.
3811
     *
3812
     * EXAMPLE: <code>
3813
     * s('fòôbàř')->shuffle(); // 'àôřbòf'
3814
     * </code>
3815
     *
3816
     * @return static
3817
     *                <p>Object with a shuffled $str.</p>
3818
     */
3819
    public function shuffle(): self
3820
    {
3821
        return static::create($this->utf8::str_shuffle($this->str), $this->encoding);
9✔
3822
    }
3823

3824
    /**
3825
     * Calculate the similarity between two strings.
3826
     *
3827
     * EXAMPLE: <code>
3828
     * </code>
3829
     *
3830
     * @param string $str <p>The delimiting string.</p>
3831
     *
3832
     * @psalm-mutation-free
3833
     *
3834
     * @return float
3835
     */
3836
    public function similarity(string $str): float
3837
    {
3838
        \similar_text($this->str, $str, $percent);
2✔
3839

3840
        return $percent;
2✔
3841
    }
3842

3843
    /**
3844
     * Returns the substring beginning at $start, and up to, but not including
3845
     * the index specified by $end. If $end is omitted, the function extracts
3846
     * the remaining string. If $end is negative, it is computed from the end
3847
     * of the string.
3848
     *
3849
     * EXAMPLE: <code>
3850
     * s('fòôbàř')->slice(3, -1); // 'bà'
3851
     * </code>
3852
     *
3853
     * @param int $start <p>Initial index from which to begin extraction.</p>
3854
     * @param int $end   [optional] <p>Index at which to end extraction. Default: null</p>
3855
     *
3856
     * @psalm-mutation-free
3857
     *
3858
     * @return static
3859
     *                <p>Object with its $str being the extracted substring.</p>
3860
     */
3861
    public function slice(int $start, ?int $end = null): self
3862
    {
3863
        return static::create(
50✔
3864
            $this->utf8::str_slice($this->str, $start, $end, $this->encoding),
50✔
3865
            $this->encoding
50✔
3866
        );
50✔
3867
    }
3868

3869
    /**
3870
     * Converts the string into an URL slug. This includes replacing non-ASCII
3871
     * characters with their closest ASCII equivalents, removing remaining
3872
     * non-ASCII and non-alphanumeric characters, and replacing whitespace with
3873
     * $separator. The separator defaults to a single dash, and the string
3874
     * is also converted to lowercase. The language of the source string can
3875
     * also be supplied for language-specific transliteration.
3876
     *
3877
     * EXAMPLE: <code>
3878
     * s('Using strings like fòô bàř')->slugify(); // 'using-strings-like-foo-bar'
3879
     * </code>
3880
     *
3881
     * @param string                $separator             [optional] <p>The string used to replace whitespace.</p>
3882
     * @param string                $language              [optional] <p>Language of the source string.</p>
3883
     * @param array<string, string> $replacements          [optional] <p>A map of replaceable strings.</p>
3884
     * @param bool                  $replace_extra_symbols [optional]  <p>Add some more replacements e.g. "£" with "
3885
     *                                                     pound ".</p>
3886
     * @param bool                  $use_str_to_lower      [optional] <p>Use "string to lower" for the input.</p>
3887
     * @param bool                  $use_transliterate     [optional]  <p>Use ASCII::to_transliterate() for unknown
3888
     *                                                     chars.</p>
3889
     *
3890
     * @psalm-mutation-free
3891
     *
3892
     * @return static
3893
     *                <p>Object whose $str has been converted to an URL slug.</p>
3894
     *
3895
     * @phpstan-param ASCII::*_LANGUAGE_CODE $language
3896
     *
3897
     * @noinspection PhpTooManyParametersInspection
3898
     */
3899
    public function slugify(
3900
        string $separator = '-',
3901
        string $language = 'en',
3902
        array $replacements = [],
3903
        bool $replace_extra_symbols = true,
3904
        bool $use_str_to_lower = true,
3905
        bool $use_transliterate = false
3906
    ): self {
3907
        return static::create(
17✔
3908
            $this->ascii::to_slugify(
17✔
3909
                $this->str,
17✔
3910
                $separator,
17✔
3911
                $language,
17✔
3912
                $replacements,
17✔
3913
                $replace_extra_symbols,
17✔
3914
                $use_str_to_lower,
17✔
3915
                $use_transliterate
17✔
3916
            ),
17✔
3917
            $this->encoding
17✔
3918
        );
17✔
3919
    }
3920

3921
    /**
3922
     * Convert the string to snake_case.
3923
     *
3924
     * EXAMPLE: <code>
3925
     * </code>
3926
     *
3927
     * @psalm-mutation-free
3928
     *
3929
     * @return static
3930
     */
3931
    public function snakeCase(): self
3932
    {
3933
        $words = \array_map(
3✔
3934
            static function (self $word) {
3✔
3935
                return $word->toLowerCase();
3✔
3936
            },
3✔
3937
            $this->words('', true)
3✔
3938
        );
3✔
3939

3940
        return new static(\implode('_', $words), $this->encoding);
3✔
3941
    }
3942

3943
    /**
3944
     * Convert a string to snake_case.
3945
     *
3946
     * EXAMPLE: <code>
3947
     * s('foo1 Bar')->snakeize(); // 'foo_1_bar'
3948
     * </code>
3949
     *
3950
     * @psalm-mutation-free
3951
     *
3952
     * @return static
3953
     *                <p>Object with $str in snake_case.</p>
3954
     */
3955
    public function snakeize(): self
3956
    {
3957
        return static::create(
40✔
3958
            $this->utf8::str_snakeize($this->str, $this->encoding),
40✔
3959
            $this->encoding
40✔
3960
        );
40✔
3961
    }
3962

3963
    /**
3964
     * Wrap the string after the first whitespace character after a given number
3965
     * of characters.
3966
     *
3967
     * EXAMPLE: <code>
3968
     * </code>
3969
     *
3970
     * @param int    $width <p>Number of characters at which to wrap.</p>
3971
     * @param string $break [optional] <p>Character used to break the string. | Default "\n"</p>
3972
     *
3973
     * @psalm-mutation-free
3974
     *
3975
     * @return static
3976
     */
3977
    public function softWrap(int $width, string $break = "\n"): self
3978
    {
3979
        return $this->lineWrapAfterWord($width, $break, false);
2✔
3980
    }
3981

3982
    /**
3983
     * Splits the string with the provided regular expression, returning an
3984
     * array of Stringy objects. An optional integer $limit will truncate the
3985
     * results.
3986
     *
3987
     * EXAMPLE: <code>
3988
     * s('foo,bar,baz')->split(',', 2); // ['foo', 'bar']
3989
     * </code>
3990
     *
3991
     * @param string $pattern <p>The regex with which to split the string.</p>
3992
     * @param int    $limit   [optional] <p>Maximum number of results to return. Default: -1 === no
3993
     *                        limit</p>
3994
     *
3995
     * @psalm-mutation-free
3996
     *
3997
     * @return static[]
3998
     *                  <p>An array of Stringy objects.</p>
3999
     *
4000
     * @phpstan-return array<int,static>
4001
     */
4002
    public function split(string $pattern, ?int $limit = null): array
4003
    {
4004
        if ($this->str === '') {
51✔
4005
            return [];
×
4006
        }
4007

4008
        if ($limit === null) {
51✔
4009
            $limit = -1;
7✔
4010
        }
4011

4012
        $array = $this->utf8::str_split_pattern($this->str, $pattern, $limit);
51✔
4013
        foreach ($array as &$value) {
51✔
4014
            $value = static::create($value, $this->encoding);
45✔
4015
        }
4016

4017
        /** @noinspection PhpSillyAssignmentInspection */
4018
        /** @var static[] $array */
4019
        $array = $array;
51✔
4020

4021
        return $array;
51✔
4022
    }
4023

4024
    /**
4025
     * Splits the string with the provided regular expression, returning an
4026
     * collection of Stringy objects. An optional integer $limit will truncate the
4027
     * results.
4028
     *
4029
     * EXAMPLE: <code>
4030
     * </code>
4031
     *
4032
     * @param string $pattern <p>The regex with which to split the string.</p>
4033
     * @param int    $limit   [optional] <p>Maximum number of results to return. Default: -1 === no
4034
     *                        limit</p>
4035
     *
4036
     * @psalm-mutation-free
4037
     *
4038
     * @return CollectionStringy|static[]
4039
     *                                    <p>An collection of Stringy objects.</p>
4040
     *
4041
     * @phpstan-return CollectionStringy<int,static>
4042
     */
4043
    public function splitCollection(string $pattern, ?int $limit = null): CollectionStringy
4044
    {
4045
        /**
4046
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the collection class
4047
         */
4048
        return CollectionStringy::create(
35✔
4049
            $this->split($pattern, $limit)
35✔
4050
        );
35✔
4051
    }
4052

4053
    /**
4054
     * Returns true if the string begins with $substring, false otherwise. By
4055
     * default, the comparison is case-sensitive, but can be made insensitive
4056
     * by setting $caseSensitive to false.
4057
     *
4058
     * EXAMPLE: <code>
4059
     * s('FÒÔbàřbaz')->startsWith('fòôbàř', false); // true
4060
     * </code>
4061
     *
4062
     * @param string $substring     <p>The substring to look for.</p>
4063
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
4064
     *
4065
     * @psalm-mutation-free
4066
     *
4067
     * @return bool
4068
     *              <p>Whether or not $str starts with $substring.</p>
4069
     */
4070
    public function startsWith(string $substring, bool $caseSensitive = true): bool
4071
    {
4072
        if ($caseSensitive) {
99✔
4073
            return $this->utf8::str_starts_with($this->str, $substring);
53✔
4074
        }
4075

4076
        return $this->utf8::str_istarts_with($this->str, $substring);
46✔
4077
    }
4078

4079
    /**
4080
     * Returns true if the string begins with any of $substrings, false otherwise.
4081
     * By default the comparison is case-sensitive, but can be made insensitive by
4082
     * setting $caseSensitive to false.
4083
     *
4084
     * EXAMPLE: <code>
4085
     * s('FÒÔbàřbaz')->startsWithAny(['fòô', 'bàř'], false); // true
4086
     * </code>
4087
     *
4088
     * @param string[] $substrings    <p>Substrings to look for.</p>
4089
     * @param bool     $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
4090
     *
4091
     * @psalm-mutation-free
4092
     *
4093
     * @return bool
4094
     *              <p>Whether or not $str starts with $substring.</p>
4095
     */
4096
    public function startsWithAny(array $substrings, bool $caseSensitive = true): bool
4097
    {
4098
        if ($caseSensitive) {
35✔
4099
            return $this->utf8::str_starts_with_any($this->str, $substrings);
23✔
4100
        }
4101

4102
        return $this->utf8::str_istarts_with_any($this->str, $substrings);
12✔
4103
    }
4104

4105
    /**
4106
     * Remove one or more strings from the string.
4107
     *
4108
     * EXAMPLE: <code>
4109
     * </code>
4110
     *
4111
     * @param string|string[] $search One or more strings to be removed
4112
     *
4113
     * @psalm-mutation-free
4114
     *
4115
     * @return static
4116
     */
4117
    public function strip($search): self
4118
    {
4119
        if (\is_array($search)) {
3✔
4120
            return $this->replaceAll($search, '');
1✔
4121
        }
4122

4123
        return $this->replace($search, '');
2✔
4124
    }
4125

4126
    /**
4127
     * Strip all whitespace characters. This includes tabs and newline characters,
4128
     * as well as multibyte whitespace such as the thin space and ideographic space.
4129
     *
4130
     * EXAMPLE: <code>
4131
     * s('   Ο     συγγραφέας  ')->stripWhitespace(); // 'Οσυγγραφέας'
4132
     * </code>
4133
     *
4134
     * @psalm-mutation-free
4135
     *
4136
     * @return static
4137
     */
4138
    public function stripWhitespace(): self
4139
    {
4140
        return static::create(
36✔
4141
            $this->utf8::strip_whitespace($this->str),
36✔
4142
            $this->encoding
36✔
4143
        );
36✔
4144
    }
4145

4146
    /**
4147
     * Remove css media-queries.
4148
     *
4149
     * EXAMPLE: <code>
4150
     * s('test @media (min-width:660px){ .des-cla #mv-tiles{width:480px} } test ')->stripeCssMediaQueries(); // 'test  test '
4151
     * </code>
4152
     *
4153
     * @psalm-mutation-free
4154
     *
4155
     * @return static
4156
     */
4157
    public function stripeCssMediaQueries(): self
4158
    {
4159
        return static::create(
2✔
4160
            $this->utf8::css_stripe_media_queries($this->str),
2✔
4161
            $this->encoding
2✔
4162
        );
2✔
4163
    }
4164

4165
    /**
4166
     * Remove empty html-tag.
4167
     *
4168
     * EXAMPLE: <code>
4169
     * s('foo<h1></h1>bar')->stripeEmptyHtmlTags(); // 'foobar'
4170
     * </code>
4171
     *
4172
     * @psalm-mutation-free
4173
     *
4174
     * @return static
4175
     */
4176
    public function stripeEmptyHtmlTags(): self
4177
    {
4178
        return static::create(
2✔
4179
            $this->utf8::html_stripe_empty_tags($this->str),
2✔
4180
            $this->encoding
2✔
4181
        );
2✔
4182
    }
4183

4184
    /**
4185
     * Convert the string to StudlyCase.
4186
     *
4187
     * EXAMPLE: <code>
4188
     * </code>
4189
     *
4190
     * @psalm-mutation-free
4191
     *
4192
     * @return static
4193
     */
4194
    public function studlyCase(): self
4195
    {
4196
        $words = \array_map(
6✔
4197
            static function (self $word) {
6✔
4198
                return $word->substr(0, 1)
6✔
4199
                    ->toUpperCase()
6✔
4200
                    ->appendStringy($word->substr(1));
6✔
4201
            },
6✔
4202
            $this->words('', true)
6✔
4203
        );
6✔
4204

4205
        return new static(\implode('', $words), $this->encoding);
6✔
4206
    }
4207

4208
    /**
4209
     * Returns the substring beginning at $start with the specified $length.
4210
     * It differs from the $this->utf8::substr() function in that providing a $length of
4211
     * null will return the rest of the string, rather than an empty string.
4212
     *
4213
     * EXAMPLE: <code>
4214
     * </code>
4215
     *
4216
     * @param int $start  <p>Position of the first character to use.</p>
4217
     * @param int $length [optional] <p>Maximum number of characters used. Default: null</p>
4218
     *
4219
     * @psalm-mutation-free
4220
     *
4221
     * @return static
4222
     *                <p>Object with its $str being the substring.</p>
4223
     */
4224
    public function substr(int $start, ?int $length = null): self
4225
    {
4226
        return static::create(
40✔
4227
            $this->utf8::substr(
40✔
4228
                $this->str,
40✔
4229
                $start,
40✔
4230
                $length,
40✔
4231
                $this->encoding
40✔
4232
            ),
40✔
4233
            $this->encoding
40✔
4234
        );
40✔
4235
    }
4236

4237
    /**
4238
     * Return part of the string.
4239
     * Alias for substr()
4240
     *
4241
     * EXAMPLE: <code>
4242
     * s('fòôbàř')->substring(2, 3); // 'ôbà'
4243
     * </code>
4244
     *
4245
     * @param int $start  <p>Starting position of the substring.</p>
4246
     * @param int $length [optional] <p>Length of substring.</p>
4247
     *
4248
     * @psalm-mutation-free
4249
     *
4250
     * @return static
4251
     */
4252
    public function substring(int $start, ?int $length = null): self
4253
    {
4254
        if ($length === null) {
3✔
4255
            return $this->substr($start);
2✔
4256
        }
4257

4258
        return $this->substr($start, $length);
3✔
4259
    }
4260

4261
    /**
4262
     * Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".
4263
     * If no match is found returns new empty Stringy object.
4264
     *
4265
     * EXAMPLE: <code>
4266
     * </code>
4267
     *
4268
     * @param string $needle       <p>The string to look for.</p>
4269
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
4270
     *
4271
     * @psalm-mutation-free
4272
     *
4273
     * @return static
4274
     */
4275
    public function substringOf(string $needle, bool $beforeNeedle = false): self
4276
    {
4277
        return static::create(
4✔
4278
            $this->utf8::str_substr_first(
4✔
4279
                $this->str,
4✔
4280
                $needle,
4✔
4281
                $beforeNeedle,
4✔
4282
                $this->encoding
4✔
4283
            ),
4✔
4284
            $this->encoding
4✔
4285
        );
4✔
4286
    }
4287

4288
    /**
4289
     * Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".
4290
     * If no match is found returns new empty Stringy object.
4291
     *
4292
     * EXAMPLE: <code>
4293
     * </code>
4294
     *
4295
     * @param string $needle       <p>The string to look for.</p>
4296
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
4297
     *
4298
     * @psalm-mutation-free
4299
     *
4300
     * @return static
4301
     */
4302
    public function substringOfIgnoreCase(string $needle, bool $beforeNeedle = false): self
4303
    {
4304
        return static::create(
4✔
4305
            $this->utf8::str_isubstr_first(
4✔
4306
                $this->str,
4✔
4307
                $needle,
4✔
4308
                $beforeNeedle,
4✔
4309
                $this->encoding
4✔
4310
            ),
4✔
4311
            $this->encoding
4✔
4312
        );
4✔
4313
    }
4314

4315
    /**
4316
     * Surrounds $str with the given substring.
4317
     *
4318
     * EXAMPLE: <code>
4319
     * s(' ͜ ')->surround('ʘ'); // 'ʘ ͜ ʘ'
4320
     * </code>
4321
     *
4322
     * @param string $substring <p>The substring to add to both sides.</P>
4323
     *
4324
     * @psalm-mutation-free
4325
     *
4326
     * @return static
4327
     *                <p>Object whose $str had the substring both prepended and appended.</p>
4328
     */
4329
    public function surround(string $substring): self
4330
    {
4331
        return static::create(
15✔
4332
            $substring . $this->str . $substring,
15✔
4333
            $this->encoding
15✔
4334
        );
15✔
4335
    }
4336

4337
    /**
4338
     * Returns a case swapped version of the string.
4339
     *
4340
     * EXAMPLE: <code>
4341
     * s('Ντανιλ')->swapCase(); // 'νΤΑΝΙΛ'
4342
     * </code>
4343
     *
4344
     * @psalm-mutation-free
4345
     *
4346
     * @return static
4347
     *                <p>Object whose $str has each character's case swapped.</P>
4348
     */
4349
    public function swapCase(): self
4350
    {
4351
        return static::create(
15✔
4352
            $this->utf8::swapCase($this->str, $this->encoding),
15✔
4353
            $this->encoding
15✔
4354
        );
15✔
4355
    }
4356

4357
    /**
4358
     * Returns a string with smart quotes, ellipsis characters, and dashes from
4359
     * Windows-1252 (commonly used in Word documents) replaced by their ASCII
4360
     * equivalents.
4361
     *
4362
     * EXAMPLE: <code>
4363
     * s('“I see…”')->tidy(); // '"I see..."'
4364
     * </code>
4365
     *
4366
     * @psalm-mutation-free
4367
     *
4368
     * @return static
4369
     *                <p>Object whose $str has those characters removed.</p>
4370
     */
4371
    public function tidy(): self
4372
    {
4373
        return static::create(
12✔
4374
            $this->ascii::normalize_msword($this->str),
12✔
4375
            $this->encoding
12✔
4376
        );
12✔
4377
    }
4378

4379
    /**
4380
     * Returns a trimmed string with the first letter of each word capitalized.
4381
     * Also accepts an array, $ignore, allowing you to list words not to be
4382
     * capitalized.
4383
     *
4384
     * EXAMPLE: <code>
4385
     * $ignore = ['at', 'by', 'for', 'in', 'of', 'on', 'out', 'to', 'the'];
4386
     * s('i like to watch television')->titleize($ignore); // 'I Like to Watch Television'
4387
     * </code>
4388
     *
4389
     * @param string[]|null $ignore            [optional] <p>An array of words not to capitalize or null.
4390
     *                                         Default: null</p>
4391
     * @param string|null   $word_define_chars [optional] <p>An string of chars that will be used as whitespace
4392
     *                                         separator === words.</p>
4393
     * @param string|null   $language          [optional] <p>Language of the source string.</p>
4394
     *
4395
     * @psalm-mutation-free
4396
     *
4397
     * @return static
4398
     *                <p>Object with a titleized $str.</p>
4399
     */
4400
    public function titleize(
4401
        ?array $ignore = null,
4402
        ?string $word_define_chars = null,
4403
        ?string $language = null
4404
    ): self {
4405
        return static::create(
23✔
4406
            $this->utf8::str_titleize(
23✔
4407
                $this->str,
23✔
4408
                $ignore,
23✔
4409
                $this->encoding,
23✔
4410
                false,
23✔
4411
                $language,
23✔
4412
                false,
23✔
4413
                true,
23✔
4414
                $word_define_chars
23✔
4415
            ),
23✔
4416
            $this->encoding
23✔
4417
        );
23✔
4418
    }
4419

4420
    /**
4421
     * Returns a trimmed string in proper title case: Also accepts an array, $ignore, allowing you to list words not to
4422
     * be capitalized.
4423
     *
4424
     * EXAMPLE: <code>
4425
     * </code>
4426
     *
4427
     * Adapted from John Gruber's script.
4428
     *
4429
     * @see https://gist.github.com/gruber/9f9e8650d68b13ce4d78
4430
     *
4431
     * @param string[] $ignore <p>An array of words not to capitalize.</p>
4432
     *
4433
     * @psalm-mutation-free
4434
     *
4435
     * @return static
4436
     *                <p>Object with a titleized $str</p>
4437
     */
4438
    public function titleizeForHumans(array $ignore = []): self
4439
    {
4440
        return static::create(
70✔
4441
            $this->utf8::str_titleize_for_humans(
70✔
4442
                $this->str,
70✔
4443
                $ignore,
70✔
4444
                $this->encoding
70✔
4445
            ),
70✔
4446
            $this->encoding
70✔
4447
        );
70✔
4448
    }
4449

4450
    /**
4451
     * Returns an ASCII version of the string. A set of non-ASCII characters are
4452
     * replaced with their closest ASCII counterparts, and the rest are removed
4453
     * by default. The language or locale of the source string can be supplied
4454
     * for language-specific transliteration in any of the following formats:
4455
     * en, en_GB, or en-GB. For example, passing "de" results in "äöü" mapping
4456
     * to "aeoeue" rather than "aou" as in other languages.
4457
     *
4458
     * EXAMPLE: <code>
4459
     * s('fòôbàř')->toAscii(); // 'foobar'
4460
     * </code>
4461
     *
4462
     * @param string $language          [optional] <p>Language of the source string.</p>
4463
     * @param bool   $removeUnsupported [optional] <p>Whether or not to remove the
4464
     *                                  unsupported characters.</p>
4465
     *
4466
     * @psalm-mutation-free
4467
     *
4468
     * @return static
4469
     *                <p>Object whose $str contains only ASCII characters.</p>
4470
     *
4471
     * @phpstan-param ASCII::*_LANGUAGE_CODE $language
4472
     */
4473
    public function toAscii(string $language = 'en', bool $removeUnsupported = true): self
4474
    {
4475
        return static::create(
23✔
4476
            $this->ascii::to_ascii(
23✔
4477
                $this->str,
23✔
4478
                $language,
23✔
4479
                $removeUnsupported
23✔
4480
            ),
23✔
4481
            $this->encoding
23✔
4482
        );
23✔
4483
    }
4484

4485
    /**
4486
     * Returns a boolean representation of the given logical string value.
4487
     * For example, <strong>'true', '1', 'on' and 'yes'</strong> will return true. <strong>'false', '0',
4488
     * 'off', and 'no'</strong> will return false. In all instances, case is ignored.
4489
     * For other numeric strings, their sign will determine the return value.
4490
     * In addition, blank strings consisting of only whitespace will return
4491
     * false. For all other strings, the return value is a result of a
4492
     * boolean cast.
4493
     *
4494
     * EXAMPLE: <code>
4495
     * s('OFF')->toBoolean(); // false
4496
     * </code>
4497
     *
4498
     * @psalm-mutation-free
4499
     *
4500
     * @return bool
4501
     *              <p>A boolean value for the string.</p>
4502
     */
4503
    public function toBoolean(): bool
4504
    {
4505
        /**
4506
         * @psalm-suppress ArgumentTypeCoercion -> maybe the string looks like an int ;)
4507
         * @phpstan-ignore-next-line
4508
         */
4509
        return $this->utf8::to_boolean($this->str);
45✔
4510
    }
4511

4512
    /**
4513
     * Converts all characters in the string to lowercase.
4514
     *
4515
     * EXAMPLE: <code>
4516
     * s('FÒÔBÀŘ')->toLowerCase(); // 'fòôbàř'
4517
     * </code>
4518
     *
4519
     * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
4520
     * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
4521
     *
4522
     * @psalm-mutation-free
4523
     *
4524
     * @return static
4525
     *                <p>Object with all characters of $str being lowercase.</p>
4526
     */
4527
    public function toLowerCase($tryToKeepStringLength = false, $lang = null): self
4528
    {
4529
        return static::create(
23✔
4530
            $this->utf8::strtolower(
23✔
4531
                $this->str,
23✔
4532
                $this->encoding,
23✔
4533
                false,
23✔
4534
                $lang,
23✔
4535
                $tryToKeepStringLength
23✔
4536
            ),
23✔
4537
            $this->encoding
23✔
4538
        );
23✔
4539
    }
4540

4541
    /**
4542
     * Converts each tab in the string to some number of spaces, as defined by
4543
     * $tabLength. By default, each tab is converted to 4 consecutive spaces.
4544
     *
4545
     * EXAMPLE: <code>
4546
     * s(' String speech = "Hi"')->toSpaces(); // '    String speech = "Hi"'
4547
     * </code>
4548
     *
4549
     * @param int $tabLength [optional] <p>Number of spaces to replace each tab with. Default: 4</p>
4550
     *
4551
     * @psalm-mutation-free
4552
     *
4553
     * @return static
4554
     *                <p>Object whose $str has had tabs switched to spaces.</p>
4555
     */
4556
    public function toSpaces(int $tabLength = 4): self
4557
    {
4558
        if ($tabLength === 4) {
18✔
4559
            $tab = '    ';
9✔
4560
        } elseif ($tabLength === 2) {
9✔
4561
            $tab = '  ';
3✔
4562
        } else {
4563
            $tab = \str_repeat(' ', $tabLength);
6✔
4564
        }
4565

4566
        return static::create(
18✔
4567
            \str_replace("\t", $tab, $this->str),
18✔
4568
            $this->encoding
18✔
4569
        );
18✔
4570
    }
4571

4572
    /**
4573
     * Return Stringy object as string, but you can also use (string) for automatically casting the object into a
4574
     * string.
4575
     *
4576
     * EXAMPLE: <code>
4577
     * s('fòôbàř')->toString(); // 'fòôbàř'
4578
     * </code>
4579
     *
4580
     * @psalm-mutation-free
4581
     *
4582
     * @return string
4583
     */
4584
    public function toString(): string
4585
    {
4586
        return (string) $this->str;
2,236✔
4587
    }
4588

4589
    /**
4590
     * Converts each occurrence of some consecutive number of spaces, as
4591
     * defined by $tabLength, to a tab. By default, each 4 consecutive spaces
4592
     * are converted to a tab.
4593
     *
4594
     * EXAMPLE: <code>
4595
     * s('    fòô    bàř')->toTabs(); // '   fòô bàř'
4596
     * </code>
4597
     *
4598
     * @param int $tabLength [optional] <p>Number of spaces to replace with a tab. Default: 4</p>
4599
     *
4600
     * @psalm-mutation-free
4601
     *
4602
     * @return static
4603
     *                <p>Object whose $str has had spaces switched to tabs.</p>
4604
     */
4605
    public function toTabs(int $tabLength = 4): self
4606
    {
4607
        if ($tabLength === 4) {
15✔
4608
            $tab = '    ';
9✔
4609
        } elseif ($tabLength === 2) {
6✔
4610
            $tab = '  ';
3✔
4611
        } else {
4612
            $tab = \str_repeat(' ', $tabLength);
3✔
4613
        }
4614

4615
        return static::create(
15✔
4616
            \str_replace($tab, "\t", $this->str),
15✔
4617
            $this->encoding
15✔
4618
        );
15✔
4619
    }
4620

4621
    /**
4622
     * Converts the first character of each word in the string to uppercase
4623
     * and all other chars to lowercase.
4624
     *
4625
     * EXAMPLE: <code>
4626
     * s('fòô bàř')->toTitleCase(); // 'Fòô Bàř'
4627
     * </code>
4628
     *
4629
     * @psalm-mutation-free
4630
     *
4631
     * @return static
4632
     *                <p>Object with all characters of $str being title-cased.</p>
4633
     */
4634
    public function toTitleCase(): self
4635
    {
4636
        return static::create(
15✔
4637
            $this->utf8::titlecase($this->str, $this->encoding),
15✔
4638
            $this->encoding
15✔
4639
        );
15✔
4640
    }
4641

4642
    /**
4643
     * Returns an ASCII version of the string. A set of non-ASCII characters are
4644
     * replaced with their closest ASCII counterparts, and the rest are removed
4645
     * unless instructed otherwise.
4646
     *
4647
     * EXAMPLE: <code>
4648
     * </code>
4649
     *
4650
     * @param bool   $strict  [optional] <p>Use "transliterator_transliterate()" from PHP-Intl | WARNING: bad
4651
     *                        performance | Default: false</p>
4652
     * @param string $unknown [optional] <p>Character use if character unknown. (default is ?)</p>
4653
     *
4654
     * @psalm-mutation-free
4655
     *
4656
     * @return static
4657
     *                <p>Object whose $str contains only ASCII characters.</p>
4658
     */
4659
    public function toTransliterate(bool $strict = false, string $unknown = '?'): self
4660
    {
4661
        return static::create(
34✔
4662
            $this->ascii::to_transliterate($this->str, $unknown, $strict),
34✔
4663
            $this->encoding
34✔
4664
        );
34✔
4665
    }
4666

4667
    /**
4668
     * Converts all characters in the string to uppercase.
4669
     *
4670
     * EXAMPLE: <code>
4671
     * s('fòôbàř')->toUpperCase(); // 'FÒÔBÀŘ'
4672
     * </code>
4673
     *
4674
     * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
4675
     * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
4676
     *
4677
     * @psalm-mutation-free
4678
     *
4679
     * @return static
4680
     *                <p>Object with all characters of $str being uppercase.</p>
4681
     */
4682
    public function toUpperCase($tryToKeepStringLength = false, $lang = null): self
4683
    {
4684
        return static::create(
26✔
4685
            $this->utf8::strtoupper($this->str, $this->encoding, false, $lang, $tryToKeepStringLength),
26✔
4686
            $this->encoding
26✔
4687
        );
26✔
4688
    }
4689

4690
    /**
4691
     * Returns a string with whitespace removed from the start and end of the
4692
     * string. Supports the removal of unicode whitespace. Accepts an optional
4693
     * string of characters to strip instead of the defaults.
4694
     *
4695
     * EXAMPLE: <code>
4696
     * s('  fòôbàř  ')->trim(); // 'fòôbàř'
4697
     * </code>
4698
     *
4699
     * @param string $chars [optional] <p>String of characters to strip. Default: null</p>
4700
     *
4701
     * @psalm-mutation-free
4702
     *
4703
     * @return static
4704
     *                <p>Object with a trimmed $str.</p>
4705
     */
4706
    public function trim(?string $chars = null): self
4707
    {
4708
        return static::create(
36✔
4709
            $this->utf8::trim($this->str, $chars),
36✔
4710
            $this->encoding
36✔
4711
        );
36✔
4712
    }
4713

4714
    /**
4715
     * Returns a string with whitespace removed from the start of the string.
4716
     * Supports the removal of unicode whitespace. Accepts an optional
4717
     * string of characters to strip instead of the defaults.
4718
     *
4719
     * EXAMPLE: <code>
4720
     * s('  fòôbàř  ')->trimLeft(); // 'fòôbàř  '
4721
     * </code>
4722
     *
4723
     * @param string $chars [optional] <p>Optional string of characters to strip. Default: null</p>
4724
     *
4725
     * @psalm-mutation-free
4726
     *
4727
     * @return static
4728
     *                <p>Object with a trimmed $str.</p>
4729
     */
4730
    public function trimLeft(?string $chars = null): self
4731
    {
4732
        return static::create(
39✔
4733
            $this->utf8::ltrim($this->str, $chars),
39✔
4734
            $this->encoding
39✔
4735
        );
39✔
4736
    }
4737

4738
    /**
4739
     * Returns a string with whitespace removed from the end of the string.
4740
     * Supports the removal of unicode whitespace. Accepts an optional
4741
     * string of characters to strip instead of the defaults.
4742
     *
4743
     * EXAMPLE: <code>
4744
     * s('  fòôbàř  ')->trimRight(); // '  fòôbàř'
4745
     * </code>
4746
     *
4747
     * @param string $chars [optional] <p>Optional string of characters to strip. Default: null</p>
4748
     *
4749
     * @psalm-mutation-free
4750
     *
4751
     * @return static
4752
     *                <p>Object with a trimmed $str.</p>
4753
     */
4754
    public function trimRight(?string $chars = null): self
4755
    {
4756
        return static::create(
39✔
4757
            $this->utf8::rtrim($this->str, $chars),
39✔
4758
            $this->encoding
39✔
4759
        );
39✔
4760
    }
4761

4762
    /**
4763
     * Truncates the string to a given length. If $substring is provided, and
4764
     * truncating occurs, the string is further truncated so that the substring
4765
     * may be appended without exceeding the desired length.
4766
     *
4767
     * EXAMPLE: <code>
4768
     * s('What are your plans today?')->truncate(19, '...'); // 'What are your pl...'
4769
     * </code>
4770
     *
4771
     * @param int    $length    <p>Desired length of the truncated string.</p>
4772
     * @param string $substring [optional] <p>The substring to append if it can fit. Default: ''</p>
4773
     *
4774
     * @psalm-mutation-free
4775
     *
4776
     * @return static
4777
     *                <p>Object with the resulting $str after truncating.</p>
4778
     */
4779
    public function truncate(int $length, string $substring = ''): self
4780
    {
4781
        return static::create(
66✔
4782
            $this->utf8::str_truncate($this->str, $length, $substring, $this->encoding),
66✔
4783
            $this->encoding
66✔
4784
        );
66✔
4785
    }
4786

4787
    /**
4788
     * Returns a lowercase and trimmed string separated by underscores.
4789
     * Underscores are inserted before uppercase characters (with the exception
4790
     * of the first character of the string), and in place of spaces as well as
4791
     * dashes.
4792
     *
4793
     * EXAMPLE: <code>
4794
     * s('TestUCase')->underscored(); // 'test_u_case'
4795
     * </code>
4796
     *
4797
     * @psalm-mutation-free
4798
     *
4799
     * @return static
4800
     *                <p>Object with an underscored $str.</p>
4801
     */
4802
    public function underscored(): self
4803
    {
4804
        return $this->delimit('_');
48✔
4805
    }
4806

4807
    /**
4808
     * Returns an UpperCamelCase version of the supplied string. It trims
4809
     * surrounding spaces, capitalizes letters following digits, spaces, dashes
4810
     * and underscores, and removes spaces, dashes, underscores.
4811
     *
4812
     * EXAMPLE: <code>
4813
     * s('Upper Camel-Case')->upperCamelize(); // 'UpperCamelCase'
4814
     * </code>
4815
     *
4816
     * @psalm-mutation-free
4817
     *
4818
     * @return static
4819
     *                <p>Object with $str in UpperCamelCase.</p>
4820
     */
4821
    public function upperCamelize(): self
4822
    {
4823
        return static::create(
49✔
4824
            $this->utf8::str_upper_camelize($this->str, $this->encoding),
49✔
4825
            $this->encoding
49✔
4826
        );
49✔
4827
    }
4828

4829
    /**
4830
     * Converts the first character of the supplied string to upper case.
4831
     *
4832
     * EXAMPLE: <code>
4833
     * s('σ foo')->upperCaseFirst(); // 'Σ foo'
4834
     * </code>
4835
     *
4836
     * @psalm-mutation-free
4837
     *
4838
     * @return static
4839
     *                <p>Object with the first character of $str being upper case.</p>
4840
     */
4841
    public function upperCaseFirst(): self
4842
    {
4843
        return static::create($this->utf8::ucfirst($this->str, $this->encoding), $this->encoding);
18✔
4844
    }
4845

4846
    /**
4847
     * Simple url-decoding.
4848
     *
4849
     * e.g:
4850
     * 'test+test' => 'test test'
4851
     *
4852
     * EXAMPLE: <code>
4853
     * </code>
4854
     *
4855
     * @psalm-mutation-free
4856
     *
4857
     * @return static
4858
     */
4859
    public function urlDecode(): self
4860
    {
4861
        return static::create(\urldecode($this->str));
1✔
4862
    }
4863

4864
    /**
4865
     * Multi url-decoding + decode HTML entity + fix urlencoded-win1252-chars.
4866
     *
4867
     * e.g:
4868
     * 'test+test'                     => 'test test'
4869
     * 'D&#252;sseldorf'               => 'Düsseldorf'
4870
     * 'D%FCsseldorf'                  => 'Düsseldorf'
4871
     * 'D&#xFC;sseldorf'               => 'Düsseldorf'
4872
     * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
4873
     * 'Düsseldorf'                   => 'Düsseldorf'
4874
     * 'D%C3%BCsseldorf'               => 'Düsseldorf'
4875
     * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
4876
     * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
4877
     *
4878
     * EXAMPLE: <code>
4879
     * </code>
4880
     *
4881
     * @psalm-mutation-free
4882
     *
4883
     * @return static
4884
     */
4885
    public function urlDecodeMulti(): self
4886
    {
4887
        return static::create($this->utf8::urldecode($this->str));
1✔
4888
    }
4889

4890
    /**
4891
     * Simple url-decoding.
4892
     *
4893
     * e.g:
4894
     * 'test+test' => 'test+test
4895
     *
4896
     * EXAMPLE: <code>
4897
     * </code>
4898
     *
4899
     * @psalm-mutation-free
4900
     *
4901
     * @return static
4902
     */
4903
    public function urlDecodeRaw(): self
4904
    {
4905
        return static::create(\rawurldecode($this->str));
1✔
4906
    }
4907

4908
    /**
4909
     * Multi url-decoding + decode HTML entity + fix urlencoded-win1252-chars.
4910
     *
4911
     * e.g:
4912
     * 'test+test'                     => 'test+test'
4913
     * 'D&#252;sseldorf'               => 'Düsseldorf'
4914
     * 'D%FCsseldorf'                  => 'Düsseldorf'
4915
     * 'D&#xFC;sseldorf'               => 'Düsseldorf'
4916
     * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
4917
     * 'Düsseldorf'                   => 'Düsseldorf'
4918
     * 'D%C3%BCsseldorf'               => 'Düsseldorf'
4919
     * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
4920
     * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
4921
     *
4922
     * EXAMPLE: <code>
4923
     * </code>
4924
     *
4925
     * @psalm-mutation-free
4926
     *
4927
     * @return static
4928
     */
4929
    public function urlDecodeRawMulti(): self
4930
    {
4931
        return static::create($this->utf8::rawurldecode($this->str));
1✔
4932
    }
4933

4934
    /**
4935
     * Simple url-encoding.
4936
     *
4937
     * e.g:
4938
     * 'test test' => 'test+test'
4939
     *
4940
     * EXAMPLE: <code>
4941
     * </code>
4942
     *
4943
     * @psalm-mutation-free
4944
     *
4945
     * @return static
4946
     */
4947
    public function urlEncode(): self
4948
    {
4949
        return static::create(\urlencode($this->str));
1✔
4950
    }
4951

4952
    /**
4953
     * Simple url-encoding.
4954
     *
4955
     * e.g:
4956
     * 'test test' => 'test%20test'
4957
     *
4958
     * EXAMPLE: <code>
4959
     * </code>
4960
     *
4961
     * @psalm-mutation-free
4962
     *
4963
     * @return static
4964
     */
4965
    public function urlEncodeRaw(): self
4966
    {
4967
        return static::create(\rawurlencode($this->str));
1✔
4968
    }
4969

4970
    /**
4971
     * Converts the string into an URL slug. This includes replacing non-ASCII
4972
     * characters with their closest ASCII equivalents, removing remaining
4973
     * non-ASCII and non-alphanumeric characters, and replacing whitespace with
4974
     * $separator. The separator defaults to a single dash, and the string
4975
     * is also converted to lowercase.
4976
     *
4977
     * EXAMPLE: <code>
4978
     * s('Using strings like fòô bàř - 1$')->urlify(); // 'using-strings-like-foo-bar-1-dollar'
4979
     * </code>
4980
     *
4981
     * @param string                $separator    [optional] <p>The string used to replace whitespace. Default: '-'</p>
4982
     * @param string                $language     [optional] <p>The language for the url. Default: 'en'</p>
4983
     * @param array<string, string> $replacements [optional] <p>A map of replaceable strings.</p>
4984
     * @param bool                  $strToLower   [optional] <p>string to lower. Default: true</p>
4985
     *
4986
     * @psalm-mutation-free
4987
     *
4988
     * @return static
4989
     *                <p>Object whose $str has been converted to an URL slug.</p>
4990
     *
4991
     * @psalm-suppress ImpureMethodCall :/
4992
     */
4993
    public function urlify(
4994
        string $separator = '-',
4995
        string $language = 'en',
4996
        array $replacements = [],
4997
        bool $strToLower = true
4998
    ): self {
4999
        // init
5000
        $str = $this->str;
32✔
5001

5002
        foreach ($replacements as $from => $to) {
32✔
5003
            $str = \str_replace($from, $to, $str);
32✔
5004
        }
5005

5006
        return static::create(
32✔
5007
            URLify::slug(
32✔
5008
                $str,
32✔
5009
                $language,
32✔
5010
                $separator,
32✔
5011
                $strToLower
32✔
5012
            ),
32✔
5013
            $this->encoding
32✔
5014
        );
32✔
5015
    }
5016

5017
    /**
5018
     * Converts the string into an valid UTF-8 string.
5019
     *
5020
     * EXAMPLE: <code>
5021
     * s('Düsseldorf')->utf8ify(); // 'Düsseldorf'
5022
     * </code>
5023
     *
5024
     * @psalm-mutation-free
5025
     *
5026
     * @return static
5027
     */
5028
    public function utf8ify(): self
5029
    {
5030
        return static::create($this->utf8::cleanup($this->str), $this->encoding);
2✔
5031
    }
5032

5033
    /**
5034
     * Convert a string into an array of words.
5035
     *
5036
     * EXAMPLE: <code>
5037
     * </code>
5038
     *
5039
     * @param string   $char_list           [optional] <p>Additional chars for the definition of "words".</p>
5040
     * @param bool     $remove_empty_values [optional] <p>Remove empty values.</p>
5041
     * @param int|null $remove_short_values [optional] <p>The min. string length or null to disable</p>
5042
     *
5043
     * @psalm-mutation-free
5044
     *
5045
     * @return static[]
5046
     *
5047
     * @phpstan-return array<int,static>
5048
     */
5049
    public function words(
5050
        string $char_list = '',
5051
        bool $remove_empty_values = false,
5052
        ?int $remove_short_values = null
5053
    ): array {
5054
        if ($remove_short_values === null) {
14✔
5055
            $strings = $this->utf8::str_to_words(
14✔
5056
                $this->str,
14✔
5057
                $char_list,
14✔
5058
                $remove_empty_values
14✔
5059
            );
14✔
5060
        } else {
5061
            $strings = $this->utf8::str_to_words(
2✔
5062
                $this->str,
2✔
5063
                $char_list,
2✔
5064
                $remove_empty_values,
2✔
5065
                $remove_short_values
2✔
5066
            );
2✔
5067
        }
5068

5069
        /** @noinspection AlterInForeachInspection */
5070
        foreach ($strings as &$string) {
14✔
5071
            $string = static::create($string);
14✔
5072
        }
5073

5074
        /** @noinspection PhpSillyAssignmentInspection */
5075
        /** @var static[] $strings */
5076
        $strings = $strings;
14✔
5077

5078
        return $strings;
14✔
5079
    }
5080

5081
    /**
5082
     * Convert a string into an collection of words.
5083
     *
5084
     * EXAMPLE: <code>
5085
     * S::create('中文空白 oöäü#s')->wordsCollection('#', true)->toStrings(); // ['中文空白', 'oöäü#s']
5086
     * </code>
5087
     *
5088
     * @param string   $char_list           [optional] <p>Additional chars for the definition of "words".</p>
5089
     * @param bool     $remove_empty_values [optional] <p>Remove empty values.</p>
5090
     * @param int|null $remove_short_values [optional] <p>The min. string length or null to disable</p>
5091
     *
5092
     * @psalm-mutation-free
5093
     *
5094
     * @return CollectionStringy|static[]
5095
     *                                    <p>An collection of Stringy objects.</p>
5096
     *
5097
     * @phpstan-return CollectionStringy<int,static>
5098
     */
5099
    public function wordsCollection(
5100
        string $char_list = '',
5101
        bool $remove_empty_values = false,
5102
        ?int $remove_short_values = null
5103
    ): CollectionStringy {
5104
        /**
5105
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the collection class
5106
         */
5107
        return CollectionStringy::create(
2✔
5108
            $this->words(
2✔
5109
                $char_list,
2✔
5110
                $remove_empty_values,
2✔
5111
                $remove_short_values
2✔
5112
            )
2✔
5113
        );
2✔
5114
    }
5115

5116
    /**
5117
     * Surrounds $str with the given substring.
5118
     *
5119
     * EXAMPLE: <code>
5120
     * </code>
5121
     *
5122
     * @param string $substring <p>The substring to add to both sides.</P>
5123
     *
5124
     * @psalm-mutation-free
5125
     *
5126
     * @return static
5127
     *                <p>Object whose $str had the substring both prepended and appended.</p>
5128
     */
5129
    public function wrap(string $substring): self
5130
    {
5131
        return $this->surround($substring);
10✔
5132
    }
5133

5134
    /**
5135
     * Returns the replacements for the toAscii() method.
5136
     *
5137
     * @psalm-mutation-free
5138
     *
5139
     * @return array<string, array<int, string>>
5140
     *                                           <p>An array of replacements.</p>
5141
     *
5142
     * @deprecated   this is only here for backward-compatibly reasons
5143
     */
5144
    protected function charsArray(): array
5145
    {
5146
        return $this->ascii::charsArrayWithMultiLanguageValues();
1✔
5147
    }
5148

5149
    /**
5150
     * Returns true if $str matches the supplied pattern, false otherwise.
5151
     *
5152
     * @param string $pattern <p>Regex pattern to match against.</p>
5153
     *
5154
     * @psalm-mutation-free
5155
     *
5156
     * @return bool
5157
     *              <p>Whether or not $str matches the pattern.</p>
5158
     */
5159
    protected function matchesPattern(string $pattern): bool
5160
    {
5161
        return $this->utf8::str_matches_pattern($this->str, $pattern);
24✔
5162
    }
5163
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc