StringHelper.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. * @throws InvalidArgumentException empty needle
  70. * @param array $needles
  71. * @param string $haystack
  72. * @return bool
  73. */
  74. public static function containsAny(array $needles, $haystack)
  75. {
  76. foreach($needles as $needle) {
  77. if(empty($needle)) {
  78. throw new \InvalidArgumentException('empty needle');
  79. } elseif(strpos($haystack, $needle) !== false) {
  80. return true;
  81. }
  82. }
  83. return false;
  84. }
  85. }