Replacing everything but letters, numbers and hyphens...

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

Moderator: General Moderators

Post Reply
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Replacing everything but letters, numbers and hyphens...

Post by Mr Tech »

Hey there,

I asked a little while back how to replace everything but numbers and letters in a string? Well, I ended up with this code:

Code: Select all

$string = preg_replace('/ї^\wa-z0-9]/i', '', $string);
The only problem is that it does not remove these: _
I would much prefer it to not remove hyphens (-)

Is there anyway I can make the above code not remove hyphens from a string of text?

Ben
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Put a " \- " in those square brackets. The " - " needs escaping because it's regex operator ;)
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

You can also generally put a "-" as the first character in the []'s and it knows to treat it as a hyphen and not as a special character. I beleive it also works that way after the ^.
so

Code: Select all

$string = preg_replace('/[^-\wa-z0-9]/i', '', $string);
should also work, or use d11wtq's suggestion.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Also

[^\-\w]

is enough since \w covers the a-z and 0-9 parts anyway ;)
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Post by Mr Tech »

w00t! thanks guys :)
dave_c00
Forum Commoner
Posts: 37
Joined: Wed May 28, 2003 6:08 am

Perfect

Post by dave_c00 »

This code looks perfect for what i need however i cannot get a result can anyone help?

Thanks

Dave
User avatar
AnarKy
Forum Contributor
Posts: 119
Joined: Tue Nov 02, 2004 1:49 am
Location: South Africa

Post the code

Post by AnarKy »

dave_c00,

Post the actual code you are using so that we can have a look.
Post Reply