StringHelper.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace fphammerle\helpers;
  3. class StringHelper
  4. {
  5. /**
  6. * @return string
  7. */
  8. public static function prepend($prefix, $text)
  9. {
  10. if(is_array($text)) {
  11. $result = [];
  12. foreach($text as $key => $value) {
  13. $result[$key] = self::prepend($prefix, $value);
  14. }
  15. return $result;
  16. } else {
  17. return ($text === null) ? null : ($prefix . $text);
  18. }
  19. }
  20. /**
  21. * @return string
  22. */
  23. public static function append($text, $postfix)
  24. {
  25. if(is_array($text)) {
  26. $result = [];
  27. foreach($text as $key => $value) {
  28. $result[$key] = self::append($value, $postfix);
  29. }
  30. return $result;
  31. } else {
  32. return ($text === null) ? null : ($text . $postfix);
  33. }
  34. }
  35. /**
  36. * @return string
  37. */
  38. public static function embed($prefix, $text, $postfix)
  39. {
  40. return self::prepend($prefix, self::append($text, $postfix));
  41. }
  42. /**
  43. * @return string
  44. */
  45. public static function embrace($brace, $text)
  46. {
  47. return self::embed($brace, $text, $brace);
  48. }
  49. /**
  50. * @return string|null
  51. */
  52. public static function implode($glue, array $pieces)
  53. {
  54. $pieces = array_filter($pieces);
  55. if(sizeof($pieces) == 0) {
  56. return null;
  57. } else {
  58. return implode($glue, $pieces);
  59. }
  60. }
  61. /**
  62. * @throws InvalidArgumentException empty needle
  63. * @param array $needles
  64. * @param string $haystack
  65. * @return bool
  66. */
  67. public static function containsAny(array $needles, $haystack)
  68. {
  69. foreach($needles as $needle) {
  70. if(empty($needle)) {
  71. throw new \InvalidArgumentException('empty needle');
  72. } elseif(strpos($haystack, $needle) !== false) {
  73. return true;
  74. }
  75. }
  76. return false;
  77. }
  78. }