phpregexstringpreg-match

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


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)`;

Solution

  • 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.