Acronym.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /*
  3. * By adding type hints and enabling strict type checking, code can become
  4. * easier to read, self-documenting and reduce the number of potential bugs.
  5. * By default, type declarations are non-strict, which means they will attempt
  6. * to change the original type to match the type specified by the
  7. * type-declaration.
  8. *
  9. * In other words, if you pass a string to a function requiring a float,
  10. * it will attempt to convert the string value to a float.
  11. *
  12. * To enable strict mode, a single declare directive must be placed at the top
  13. * of the file.
  14. * This means that the strictness of typing is configured on a per-file basis.
  15. * This directive not only affects the type declarations of parameters, but also
  16. * a function's return type.
  17. *
  18. * For more info review the Concept on strict type checking in the PHP track
  19. * <link>.
  20. *
  21. * To disable strict typing, comment out the directive below.
  22. */
  23. declare(strict_types=1);
  24. function acronym(string $text): string
  25. {
  26. $parts = array_filter(mb_split("[^\w']", $text));
  27. if (count($parts) <= 1) {
  28. return "";
  29. }
  30. $parts2 = [];
  31. foreach ($parts as $part) {
  32. $first = mb_substr($part, 0, 1);
  33. if (mb_strlen($part) == 1) {
  34. $parts2[] = $first;
  35. continue;
  36. }
  37. $first = mb_strtoupper($first);
  38. $part = $first . mb_substr($part, 1);
  39. $part = mb_ereg_replace("[a-z]", " ", $part);
  40. $subs = array_filter(mb_split("[\s]", $part));
  41. foreach ($subs as $sub) {
  42. $parts2[] = $sub;
  43. }
  44. }
  45. $reduced = array_reduce($parts2, function($accu, $v) { return $accu . mb_substr($v, 0, 1); } );
  46. return mb_strtoupper($reduced);
  47. }