Regular Expression help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
irishmike2004
Forum Contributor
Posts: 119
Joined: Mon Nov 15, 2004 3:54 pm
Location: Lawrence, Kansas

Regular Expression help

Post by irishmike2004 »

I am working with the preg_replace function and I can't seem to get the variable trimmed quite right. We solved the problem as long as the PHP script is run for my town always, but we want to use it in other locations as well.

The data inside the variable (I call $location) is as follows:

Shawnee, KS (66214)

We want to loose the space and (66214)... the code I tried is this:

Code: Select all

$location = preg_replace(' (ї0-9+])','', $location);
	$location = trim($location);
This makes the following output:

Shawnee, KS ()

I am not sure being as I am not good at defining regular expressions, can someone tell me what is wrong with my replace command.

earlier someone suggested that I use str_replace but that will break whenever we change the zipcode of the weather XML feed.

Thanks,
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

try to escape ( and )
irishmike2004
Forum Contributor
Posts: 119
Joined: Mon Nov 15, 2004 3:54 pm
Location: Lawrence, Kansas

Tried Escapes and nothing

Post by irishmike2004 »

The first sequence I tried was this:

Code: Select all

$location = preg_replace(' \(ї0-9+]\)','', $location);
This takes the whole string away

the next one was this

Code: Select all

$location = preg_replace(' (\ї0-9+\])','', $location);
No Dice

Then I tried doubling the () with escapes like:

Code: Select all

$location = preg_replace(' \((ї0-9+])\)','', $location);
all this before I posted :-) Nothing I can think of seems to be working not sure if I am even (again) forming the pattern correctly.
DrHoliday
Forum Newbie
Posts: 11
Joined: Mon Dec 06, 2004 5:12 pm
Location: Germany

Post by DrHoliday »

The + sign has to go outside the [] (because you want to repeat the whole thing). Also i think you forgot the limiters (although i don't know if they are really needed). Try this:

Code: Select all

$location = preg_replace('/ \(ї0-9]+\)/', '', $location);
Wolfgang
irishmike2004
Forum Contributor
Posts: 119
Joined: Mon Nov 15, 2004 3:54 pm
Location: Lawrence, Kansas

Post by irishmike2004 »

That worked, problem solved. Thanks to all.
Post Reply