-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathreplace_ci.php
38 lines (31 loc) · 1.03 KB
/
replace_ci.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
declare(strict_types=1);
namespace Psl\Str;
use Psl\Regex;
use function preg_quote;
use function preg_split;
/**
* Returns the '$haystack' string with all occurrences of `$needle` replaced by
* `$replacement` (case-insensitive).
*
* @pure
*
* @throws Exception\InvalidArgumentException if $needle is not a valid UTF-8 string.
*/
function replace_ci(string $haystack, string $needle, string $replacement, Encoding $encoding = Encoding::Utf8): string
{
if ('' === $needle || null === search_ci($haystack, $needle, 0, $encoding)) {
return $haystack;
}
try {
/** @var list<string> */
$pieces = Regex\Internal\call_preg('preg_split', static fn() => preg_split(
'{' . preg_quote($needle, '/') . '}iu',
$haystack,
-1,
));
} catch (Regex\Exception\RuntimeException|Regex\Exception\InvalidPatternException $error) {
throw new Exception\InvalidArgumentException($error->getMessage(), previous: $error);
}
return join($pieces, $replacement);
}