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.
Find:
(?<!^)((?<![[:upper:]])[[:upper:]]|[[:upper:]](?![[:upper:]]))
Replace:
$1
note the space before $1
Edit: fix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With