开发者

Check a variable using regex

开发者 https://www.devze.com 2023-01-16 03:53 出处:网络
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 -.

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 re开发者_运维技巧gex? 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?


this regex is pretty common these days.

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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号