markzzz
markzzz

Reputation: 47945

Check a variable using regex

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?

Upvotes: 6

Views: 4049

Answers (3)

Gumbo
Gumbo

Reputation: 655239

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.

Upvotes: 2

RobertPitt
RobertPitt

Reputation: 57268

this regex is pretty common these days.

if(preg_match('/^[a-z0-9\-\_]+$/i',$username))
{
   // Ok
}

Upvotes: 9

tomsseisums
tomsseisums

Reputation: 13367

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

Upvotes: 1

Related Questions