1

I have two words combined like KitnerCoster And I want to add a space in the middle, is there any sort of trick anyone knows if separating two words that are both capitalized and that is the only difference.

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
Steven
  • 13,250
  • 33
  • 95
  • 147

2 Answers2

4

Using regular expressions you could do something like

s/([a-z])([A-Z])/'$1 $2'/g

However my first trial to write a regular expression usually fails so you might have to correct one or the other part.

How do you want to handle a 1-character long word? Like 'X' in FooXBar? The X will not be recognized as a separate word by the above regular expression.

chiccodoro
  • 14,407
  • 19
  • 87
  • 130
  • +1 because I too rarelly write a regular expression which works on the first trial. – Fernando Briano Aug 06 '10 at 13:57
  • Changing it to a preg_compatible regex (the solution is fine, but the question was about PHP): `preg_replace('/([a-z])([A-Z])/', '$1 $2', $string);`... – ircmaxell Aug 06 '10 at 13:58
3

Do you care if the first word is capitalized? If not, do

// ASCII
preg_replace('/([a-z])([A-Z])/', '$1 $2', $string)
preg_replace('/([[:lower:]])([[:upper:]])/', '$1 $2', $string)

// Unicode (UTF-8)
preg_replace('/(\p{Ll})(\p{Lu})/u', '$1 $2', $string)

If you do care, and want to fix KitnerCostner but leave kitnerCostner alone, then do

// ASCII
preg_replace('/\b([A-Z]\S*[a-z])([A-Z])/', '$1 $2', $string)
preg_replace('/\b([[:upper:]]\S*[[:lower:]])([[:upper:]])/', '$1 $2', $string)

// Unicode (UTF-8)
preg_replace('/\b(\p{Lu}\S*\p{Ll})(\p{Lu})/u', '$1 $2', $string)

I've given versions that only match ASCII letters and ones that match all Unicode characters. The Unicode ones are available in PHP 5.1.0.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578