Split camelCase word into words with php preg_match (Regular Expression)

Good-bye picture Good-bye · Dec 23, 2010 · Viewed 36k times · Source

How would I go about splitting the word:

oneTwoThreeFour

into an array so that I can get:

one Two Three Four

with preg_match ?

I tired this but it just gives the whole word

$words = preg_match("/[a-zA-Z]*(?:[a-z][a-zA-Z]*[A-Z]|[A-Z][a-zA-Z]*[a-z])[a-zA-Z]*\b/", $string, $matches)`;

Answer

codaddict picture codaddict · Dec 23, 2010

You can also use preg_match_all as:

preg_match_all('/((?:^|[A-Z])[a-z]+)/',$str,$matches);

Explanation:

(        - Start of capturing parenthesis.
 (?:     - Start of non-capturing parenthesis.
  ^      - Start anchor.
  |      - Alternation.
  [A-Z]  - Any one capital letter.
 )       - End of non-capturing parenthesis.
 [a-z]+  - one ore more lowercase letter.
)        - End of capturing parenthesis.