Forum Moderators: coopster
In a string how would I replace a space between words that start with a capital letter?
For example
Before: President George Bush is in New York today.
After: President_George_Bush is in New_York today.
Don’t ask me why I need such a weird thing! Well need to find special names in a string. Not the best way to accomplish this probably, but the best and fastest I can think of.
preg_replace is probably the way to go? but I am not good at all when it comes to regular expressions.
$string = preg_replace('/([A-Z][a-z]+)\s\s+([A-Z][a-z]+)/', '$1_$2', $string);
the '\s\s+' reduces multiple whitespace to a '_', so you should change it if you don't want tabs, newlines, multiple blanks, etc between words.
it won't work if you have a single upper case character such as "The Original G", but you can tweak it for that by changing the '[a-z]+' to '[a-z]*'.