Guest User

Untitled

a guest
Jul 22nd, 2018
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. <?php
  2. /**
  3. * Splits up a string into an array similar to the explode() function but according to CamelCase.
  4. * Uppercase characters are treated as the separator but returned as part of the respective array elements.
  5. * @author Charl van Niekerk <charlvn@charlvn.za.net>
  6. * @param string $string The original string
  7. * @param bool $lower Should the uppercase characters be converted to lowercase in the resulting array?
  8. * @return array The given string split up into an array according to the case of the individual characters.
  9. */
  10.  
  11. function explodeCase($string, $lower = true) {
  12. // Initialise the array to be returned
  13. $array = array();
  14.  
  15. // Initialise a temporary string to hold the current array element before it's pushed onto the end of the array
  16. $segment = '';
  17.  
  18. // Loop through each character in the string
  19. foreach (str_split($string) as $char) {
  20. // If the current character is uppercase
  21. if (ctype_upper($char)) {
  22. // If the old segment is not empty (for when the original string starts with an uppercase character)
  23. if ($segment) {
  24. // Push the old segment onto the array
  25. $array[] = $segment;
  26. }
  27.  
  28. // Set the character (either uppercase or lowercase) as the start of the new segment
  29. $segment = $lower ? strtolower($char) : $char;
  30. } else { // If the character is lowercase or special
  31. // Add the character to the end of the current segment
  32. $segment .= $char;
  33. }
  34. }
  35.  
  36. // If the last segment exists (for when the original string is empty)
  37. if ($segment) {
  38. // Push it onto the array
  39. $array[] = $segment;
  40. }
  41.  
  42. // Return the resulting array
  43. return $array;
  44. }
  45.  
  46. ?>
Add Comment
Please, Sign In to add comment