using regex to uppercase certain words within strings ...

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Gordon Werner
Forum Newbie
Posts: 3
Joined: Tue Apr 03, 2007 4:14 pm

using regex to uppercase certain words within strings ...

Post by Gordon Werner »

Good afternoon.

I apologize if this has been asked before but I am not sure what to search for.


I am parsing files uploaded by users that sometimes type in UPPERCASE ONLY. I can change the case of words with strtolower, ucwords, etc ... but how do I do the following?

Lets say that I ucwords a string "14 SSW OMAHA" ... this would then become "14 Ssw Omaha".

What do I need to do to make the "Ssw" into "SSW"

the possibilities are:

Nw
Ne
Sw
Se
Nnw
Nne
Ssw
Sse


Any help would be appreciated.


Thanks

G.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

What have you tried so far?
Gordon Werner
Forum Newbie
Posts: 3
Joined: Tue Apr 03, 2007 4:14 pm

Post by Gordon Werner »

well ...


I can change them all individually

$location = ereg_replace('Ssw' , 'SSW ', $location);
$location = ereg_replace('Sse' , 'SSE ', $location);
etc ...

but I would like to know if it is possible to have one statements that will change them all regardless of which compass point they supply in their text.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

I'm sure there is a string function which would help you. Have you checked?
Gordon Werner
Forum Newbie
Posts: 3
Joined: Tue Apr 03, 2007 4:14 pm

Post by Gordon Werner »

astions wrote:I'm sure there is a string function which would help you. Have you checked?
if I knew where in the string the compass point was located ... sure ... but it could be anywhere in the string being checked.


I just want to avoid running the string through 8 separate regex checks ...
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

Ah I see. You can put them all into an array and use str_replace, if you have them already set to a known state.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

Code: Select all

$text = "14 Ssw Omaha";

echo preg_replace_callback('#[nNsS][nNsS]?[we]#',create_function('$m','return strtoupper($m[0]);'),$text);
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

The pattern given my Kieran will find a match in "new york."
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

quite right - my mistake!

Code: Select all

#\b[nNsS][nNsS]?[we]\b#
Thanks feyd :-)
Post Reply