4

I have a string: CamelCaseString

I want to explode(), split(), or some better method on capital letters to break this string down into the individual words.

What's the simplest way to do this?

--- SOLUTION UPDATE ---

This link is to a slightly different question, but I think the answer will generally be more useful than the answers to the current question on this page: How can I add a space in string at capital letters, but keep continuous capitals together using PHP and a Regex?

Community
  • 1
  • 1
T. Brian Jones
  • 13,002
  • 25
  • 78
  • 117
  • 1
    The problem with the normal `explode()` function is that it will remove the so called "needle" (in your case the capital letter(s)). So the usual explode wont do the job. – Manuel Aug 03 '11 at 00:02
  • Yeah, I tried `preg_split('/[ABCDEFGHIJKLMNOPRSTUVWXYZ]/', "CamelCaseString", -1, PREG_SPLIT_NO_EMPTY)` But that returns an array without the upper case characters – Ruan Mendes Aug 03 '11 at 00:07

3 Answers3

13

You should use regular expressions. Try this: preg_match_all('/[A-Z][^A-Z]*/', "CamelCaseString", $results);

The array containing all the words will be saved in $results[0].

Ivan
  • 1,801
  • 2
  • 23
  • 40
  • That's true, $results will be: `Array ( [0] => Array ( [0] => Camel [1] => Case [2] => String ) )` – Ivan Aug 03 '11 at 00:09
  • 1
    It won't work for a string like, say, "MySQL". It'll give you "My", "S", "Q", "L", which may not be what you want – Flambino Aug 03 '11 at 00:15
  • I also had to check to make sure the string is not all caps (every letter splits), is not all lower case (all data is lost), and a few other things. It's not perfect, but it's pretty good. – T. Brian Jones Aug 03 '11 at 00:35
  • see this question instead for an answer that will generally be more useful: http://stackoverflow.com/questions/8611617/how-can-i-add-a-space-in-string-at-capital-letters-but-keep-continuous-capitals – T. Brian Jones Dec 28 '11 at 22:24
8

This seems to work too

$split = preg_split("/(?<=[a-z])(?![a-z])/", "CamelCaseString", -1, PREG_SPLIT_NO_EMPTY);

And it won't break up longer runs of uppercase letters. I.e. "MySQL", will become "My" and "SQL"

Flambino
  • 18,507
  • 2
  • 39
  • 58
-1

The split() function has been deprecated so I would look for a solution that uses some other function.

Night Owl
  • 4,198
  • 4
  • 28
  • 37
  • Well, yes, he was specifically asking for another solution than `split` – Flambino Aug 03 '11 at 00:13
  • His question has been edited. It originally asked for how to do it with split(). Thanks for the down vote when my point if perfectly valid. – Night Owl Aug 03 '11 at 00:23