Welcome to WebmasterWorld Guest from 54.158.143.40

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

regular expressions: preg replace

   
10:22 pm on Jan 31, 2007 (gmt 0)

10+ Year Member



Hello, I would really appreciate if someone could put me into the right path with this.

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.

11:54 pm on Jan 31, 2007 (gmt 0)

WebmasterWorld Administrator phranque is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month



try this:
$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]*'.

2:04 am on Feb 1, 2007 (gmt 0)

10+ Year Member



Many thanks Phranque. Will try it.