Avatar of bearclaws75
bearclaws75
 asked on

PHP: how do I insert a space before each capital letter in a string?

I have a field in a mysql database that contains a file name which looks like this:

ThisIsMyFile.gif

...and I need to add a new field which contains the English title of this file, like this:

This Is My File

I'm thinking I can write a PHP script to reformat the string and update the record...but am not what the most efficient solution would be. Any thoughts?

I'm basically looking for the PHP script (unless you can recommend a better solution).
PHP

Avatar of undefined
Last Comment
ddrudik

8/22/2022 - Mon
slouko

$string = preg_replace("/([A-Z])/"," \\1",$string);
ddrudik

There's a number of ways this can be done, if you want to avoid using capture groups in your expression:
$string = preg_replace("/(?=[A-Z])/"," ",$string);

Open in new window

ASKER CERTIFIED SOLUTION
Waschman

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
ddrudik

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
bearclaws75

ASKER
Thanks, Waschman. This worked great!

ddrudik - I think you're solution is most effecient but it only works in PHP 5.2.0 (which I'm not running on this particular site). I'll be sure to try it in the future.
Your help has saved me hundreds of hours of internet surfing.
fblack61
Waschman

Because I didn't thought of that. I know pathinfo exists but it didn't come to my mind when I first wrote the code.
ddrudik

bearclaws75, thanks for the question and the points.  The version is the one caveat with the pathinfo solution, too bad it wouldn't work out for your site.