Page 1 of 1

Replacing everything but letters, numbers and hyphens...

Posted: Wed Jul 20, 2005 6:01 am
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

Posted: Wed Jul 20, 2005 7:03 am
by Chris Corbyn
Put a " \- " in those square brackets. The " - " needs escaping because it's regex operator ;)

Posted: Wed Jul 20, 2005 10:27 am
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.

Posted: Wed Jul 20, 2005 12:06 pm
by Chris Corbyn
Also

[^\-\w]

is enough since \w covers the a-z and 0-9 parts anyway ;)

Posted: Thu Jul 21, 2005 12:22 am
by Mr Tech
w00t! thanks guys :)

Perfect

Posted: Tue Aug 02, 2005 7:47 am
by dave_c00
This code looks perfect for what i need however i cannot get a result can anyone help?

Thanks

Dave

Post the code

Posted: Tue Aug 02, 2005 7:55 am
by AnarKy
dave_c00,

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