tags:

views:

35

answers:

3

Hi.

Im about to create a registration form for my website. I need to check the variable, and accept it only if contains letter, number, _ or -.

How can do it with regex? I used to work with them with preg_replace(), but i think this is not the case. Also, i know that the "ereg" function is dead. Any solutions?

+1  A: 

Use preg_match:

preg_match('/^[\w-]+$/D', $str)

Here \w describes letters, digits and the _, so [\w-]+ matches one or more letters, digits, _, and -. ^ and $ are so called anchors that denote the begin and end of the string respectively. The D modifier avoids that $ really matches the end of the string and is not followed by a line break.

Note that the letter and digits that are matched by \w depend on the current locale and might match other letter or digits than just [a-zA-Z0-9]. So if you just want these, use them explicitly. And if you want to allow more than these, you could also try character classes that are describes by Unicode character properties like \p{L} for all Unicode letters.

Gumbo
A: 

Try preg_match(). http://php.net/manual/en/function.preg-match.php

Tom
+1  A: 

this regex is pretty common these days.

if(preg_match('/^[a-z0-9\-\_]+$/i',$username))
{
   // Ok
}
RobertPitt
perfect! tnx! i need also a empty space for the "surname" tag, so i add it ( preg_match('/^[a-z0-9\-\_ ]+$/i',$name )
markzzz
you should keep the surname separate, so you have to boxes 3 boxes, 1 for username, 1 for first name, 1 for last name and so on, this is because you have more specific control over the user data.
RobertPitt
yeah of course! i've add all of them :) just, for empty space is sufficent add " " in the regex, isnt it?
markzzz
just add a s after the I modifier like so `/^[a-z0-9\-\_]+$/is` this tell's it to ignore spaces.
RobertPitt
Actually, adding an 's' pattern modifier tells PCRE to allow the dot metacharacter ('.') to match anything including newlines. Normally, '.' matches everything except newlines. In this case, the poster simply wants to add a space to the character set, as he suggests.
mr. w
great point, i did know about this but it slipped my mind! +1
RobertPitt