StringHelper.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 = null)
  53. {
  54. if($pieces === null) {
  55. return null;
  56. } else {
  57. $pieces = array_filter(
  58. $pieces,
  59. function($piece) { return $piece !== null; }
  60. );
  61. if(sizeof($pieces) == 0) {
  62. return null;
  63. } else {
  64. return implode($glue, $pieces);
  65. }
  66. }
  67. }
  68. /**
  69. * @return string|null
  70. */
  71. public static function unite(array $pieces = null)
  72. {
  73. return self::implode('', $pieces);
  74. }
  75. /**
  76. * @throws InvalidArgumentException empty needle
  77. * @param array $needles
  78. * @param string $haystack
  79. * @return bool
  80. */
  81. public static function containsAny(array $needles, $haystack)
  82. {
  83. foreach($needles as $needle) {
  84. if(empty($needle)) {
  85. throw new \InvalidArgumentException('empty needle');
  86. } elseif(strpos($haystack, $needle) !== false) {
  87. return true;
  88. }
  89. }
  90. return false;
  91. }
  92. }