ryanzec
ryanzec

Reputation: 28040

Regex To Break Up camelCase String PHP

Let say I have the following string:

getPasswordLastChangedDatetime

How would I be able to split that up by capital letters so that I would be able to get:

get
Password
Last
Changed
Datetime

Upvotes: 4

Views: 2982

Answers (7)

azat
azat

Reputation: 3565

preg_split('@(?=[A-Z])@', 'asAs')

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816580

If you only care about ASCII characters:

$parts = preg_split("/(?=[A-Z])/", $str);

DEMO

The (?= ..) construct is called lookahead [docs].

This works if the parts only contain a capital character at the beginning. It gets more complicated if you have things like getHTMLString. This could be matched by:

$parts = preg_split("/((?<=[a-z])(?=[A-Z])|(?=[A-Z][a-z]))/", $str);

DEMO

Upvotes: 7

Artefacto
Artefacto

Reputation: 97835

For instance:

(?:^|\p{Lu})\P{Lu}*

Upvotes: 1

Bob Vale
Bob Vale

Reputation: 18474

 preg_split("/(?<=[a-z])(?=[A-Z])/",$password));

Upvotes: 0

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56172

Use this: [a-z]+|[A-Z][a-z]* or \p{Ll}+|\p{Lu}\p{Ll}*

Upvotes: 0

ryanzec
ryanzec

Reputation: 28040

Asked this a little too soon, found this:

preg_replace('/(?!^)[[:upper:]]/',' \0',$test);

Upvotes: 1

dynamic
dynamic

Reputation: 48121

No need to over complicated solution. This does it

preg_replace('/([A-Z])/',"\n".'$1',$string);

This doens't take care of acronyms of course

Upvotes: 0

Related Questions