diff --git a/php/src/str.php b/php/src/str.php index b0f3497..347726b 100644 --- a/php/src/str.php +++ b/php/src/str.php @@ -268,6 +268,21 @@ class str { $s .= $prefix.$text.$suffix; } + /** + * dans $s, faire les remplacements $key => $value du tableau $replaces + * + * si $verifix_order, le tableau est réordonné par taille de chaine source + */ + static final function replace(?string $s, ?array $replaces, bool $verifix_order=true): ?string { + if ($s === null || $replaces === null) return $s; + if ($verifix_order) { + uksort($replaces, function ($a, $b) { + return -cv::compare(strlen($a), strlen($b)); + }); + } + return str_replace(array_keys($replaces), array_values($replaces), $s); + } + /** si $text est non vide, ajouter $prefix$text$suffix à $s en séparant la valeur avec un espace */ static final function add(?string &$s, ?string $text, ?string $prefix=null, ?string $suffix=null): void { self::addsep($s, " ", $text, $prefix, $suffix); diff --git a/php/tests/strTest.php b/php/tests/strTest.php index 2d69303..c03997e 100644 --- a/php/tests/strTest.php +++ b/php/tests/strTest.php @@ -5,7 +5,22 @@ namespace nulib; use nulib\tests\TestCase; class strTest extends TestCase { - function testSplit_tokens() { + function test_replace() { + self::assertSame("premier deuxieme", str::replace("first second", [ + "first" => "premier", + "second" => "deuxieme", + ])); + self::assertSame("avant OK", str::replace("prefix prefixsuffix", [ + "prefix" => "avant", + "prefixsuffix" => "OK", + ])); + self::assertSame("avant avantsuffix", str::replace("prefix prefixsuffix", [ + "prefix" => "avant", + "prefixsuffix" => "OK", + ], false)); + } + + function test_split_tokens() { self::assertNull(str::split_tokens(null)); self::assertSame([], str::split_tokens("")); self::assertSame(["token"], str::split_tokens("token")); @@ -13,7 +28,7 @@ class strTest extends TestCase { self::assertSame(["t", "u", "v", "w"], str::split_tokens("\nt\n\nu\r\nv\rw")); } - function testCamel2us() { + function test_camel2us() { self::assertSame("a", str::camel2us("a")); self::assertSame("aa", str::camel2us("aa")); self::assertSame("aaa", str::camel2us("aaa"));