homepage Welcome to WebmasterWorld Guest from 54.167.138.53
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
regular expressions: preg replace
enotalone




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

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.

 

phranque




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

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]*'.

enotalone




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

Many thanks Phranque. Will try it.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved