Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a space in string at capital letters, but keep continuous capitals together using PHP and a Regex?

Tags:

string

regex

php

I want to add a space to a string on capital letters using a PHP method like preg_replace() and a regex, but I only want to add a space on the first capital letter when they are continuous. I also would like the regex to know that the last capital in a continuous string of capitals should be the next capital to put a space before.

These strings are examples:

TodayILiveInTheUSAWithSimon
USAToday
IAmSOOOBored

become:

 Today I Live In The USA With Simon
 USA Today
 I Am SOOO Bored

Can this be done, and how?

This question ( Regular expression, split string by capital letter but ignore TLA ), seems to accomplish this with .net.

WORKING SOLUTION

Here is the complete code that I use:

$string = 'TodayILiveInTheUSAWithSimon';
$regex = '/(?<!^)((?<![[:upper:]])[[:upper:]]|[[:upper:]](?![[:upper:]]))/';
$string = preg_replace( $regex, ' $1', $string );

Both of these regex's work:

/(?<!^)((?<![[:upper:]])[[:upper:]]|[[:upper:]](?![[:upper:]]))/
/((?<=[a-z])(?=[A-Z])|(?=[A-Z][a-z]))/

The first one is from @Regexident's solution below, and is very very slightly faster than the second one.

like image 395
T. Brian Jones Avatar asked Dec 23 '11 02:12

T. Brian Jones


1 Answers

Find:

(?<!^)((?<![[:upper:]])[[:upper:]]|[[:upper:]](?![[:upper:]]))

Replace:

 $1

note the space before $1

Edit: fix.

like image 149
Regexident Avatar answered Oct 24 '22 02:10

Regexident