Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one break a string down by capital letters with PHP?

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?

like image 986
T. Brian Jones Avatar asked Dec 01 '22 08:12

T. Brian Jones


2 Answers

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

like image 182
Ivan Avatar answered Dec 04 '22 16:12

Ivan


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"

like image 45
Flambino Avatar answered Dec 04 '22 14:12

Flambino