Page 1 of 1

using regex to uppercase certain words within strings ...

Posted: Tue Apr 03, 2007 4:21 pm
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.

Posted: Tue Apr 03, 2007 4:27 pm
by feyd
What have you tried so far?

Posted: Tue Apr 03, 2007 4:34 pm
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.

Posted: Tue Apr 03, 2007 4:38 pm
by Benjamin
I'm sure there is a string function which would help you. Have you checked?

Posted: Tue Apr 03, 2007 4:48 pm
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 ...

Posted: Tue Apr 03, 2007 5:10 pm
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.

Posted: Tue Apr 03, 2007 11:23 pm
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);

Posted: Wed Apr 04, 2007 7:27 am
by feyd
The pattern given my Kieran will find a match in "new york."

Posted: Wed Apr 04, 2007 9:01 am
by Kieran Huggins
quite right - my mistake!

Code: Select all

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