Jump to content

Help matching all symbols except defined

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
Torrodon

Torrodon

    Newbie

  • Members
  • Pip
  • 2 posts
I need to match all symbols except letters, numbers, "_", " ", "-", "&"? I tried the following but it is not working:
preg_match_all ( '/[^a-z0-9_ -&]/i' , $string , $matches );


#2
Guest_Jordan_*

Guest_Jordan_*
  • Guests
You need to escape your space, -, and &. You also probably want to include uppercase letters also?

preg_match_all ( '/[^A-Za-z0-9_\ \-\&]/i' , $string , $matches );  

Note, this is untested.

#3
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
Jordan, you don't need to escape the space or ampersand. You only need to escape characters with special meaning like the hyphen inside a character class (or you can place the hyphen at the end). Also the `i' modifier at the end makes the expression case insensitive so the A-Z is redundant. I would use
'/[^\w\s&-]/i'
It should do the same thing, but its a lot easier to read.

The meta character \w matches any alphanumeric character plus the underscore
The meta character \s matches a space

Note: This expression only matches one character. If you want it to match more than one you need to add a star or plus quantifier to the character class.

#4
Torrodon

Torrodon

    Newbie

  • Members
  • Pip
  • 2 posts
grrr i forgot '-' is special symbol inside [] and i have to escape it
thanks