Strings.replace().phpt 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. /**
  3. * Test: Nette\Utils\Strings::replace()
  4. */
  5. declare(strict_types=1);
  6. use Nette\Utils\Strings;
  7. use Tester\Assert;
  8. require __DIR__ . '/../bootstrap.php';
  9. class Test
  10. {
  11. public static function cb()
  12. {
  13. return '@';
  14. }
  15. }
  16. Assert::same('hello world!', Strings::replace('hello world!', '#([E-L])+#', '#'));
  17. Assert::same('#o wor#d!', Strings::replace('hello world!', ['#([e-l])+#'], '#'));
  18. Assert::same('#o wor#d!', Strings::replace('hello world!', '#([e-l])+#', '#'));
  19. Assert::same('@o wor@d!', Strings::replace('hello world!', '#[e-l]+#', fn() => '@'));
  20. Assert::same('@o wor@d!', Strings::replace('hello world!', '#[e-l]+#', Closure::fromCallable('Test::cb')));
  21. Assert::same('@o wor@d!', Strings::replace('hello world!', ['#[e-l]+#'], Closure::fromCallable('Test::cb')));
  22. Assert::same('@o wor@d!', Strings::replace('hello world!', '#[e-l]+#', ['Test', 'cb']));
  23. Assert::same('#@ @@@#d!', Strings::replace('hello world!', [
  24. '#([e-l])+#' => '#',
  25. '#[o-w]#' => '@',
  26. ]));
  27. Assert::same(' !', Strings::replace('hello world!', '#\w#'));
  28. Assert::same(' !', Strings::replace('hello world!', ['#\w#']));
  29. // flags & callback
  30. Assert::same('hell0o worl9d!', Strings::replace('hello world!', '#[e-l]+#', fn($m) => implode('', $m[0]), captureOffset: true));
  31. Assert::same('žl1uťoučk7ý k10ůň!', Strings::replace('žluťoučký kůň!', '#[e-l]+#u', fn($m) => implode('', $m[0]), captureOffset: true, utf8: true));
  32. Strings::replace('hello world!', '#e(x)*#', fn($m) => Assert::null($m[1]), unmatchedAsNull: true);
  33. // utf-8 without modifier
  34. Assert::same('* *', Strings::replace('Россия агрессор', '#\w+#', fn() => '*', utf8: true));
  35. Assert::same('* *', Strings::replace('Россия агрессор', '#\w+#', '*', utf8: true));
  36. Assert::same('* *', Strings::replace('Россия агрессор', ['#\w+#'], '*', utf8: true));