简体   繁体   中英

Use Regular Expression to Allow “Numbers, Letters and 3 Spaces” in Username Field

Allow letters, numbers and spaces (3 spaces maximum). How can i do it using regular expression?

I will the regular expression in PHP.

if(eregi("...HERE...", $_POST['txt_username']))
{
   //do something
}

How about this?

/^([^\W_]*\s){0,3}[^\W_]*$/

No catastrophic backtracking, since the ([^\\W_]*\\s) groups are clearly delimited.

Edit: Adopting tchrist 's unicode-friendly version: /^([\\pN\\pL\\pM]*\\s){0,3}[\\pN\\pL\\pM]*$/

You could use:

if(preg_match('@^(\w*\s){0,3}\w*$@', $_POST['txt_username)) {
    // do something
}

See it in action on: rubular.com


Note: \\w includes the underscore ( _ ). If you don't want it, you can use:

if(preg_match('@^([^\W_]*\s){0,3}[^\W_]*$@', $_POST['txt_username)) {
    // do something
}

Instead.

EDIT: Since the OP decided to accept my answer, I added Justin's improvements.

  • If you don't want to consecutive spaces, and no spaces near the edges, you can try:

     preg_match("#^\\w+(?: \\w+){0,3}$#", "123 4 5", $matches); if($matches) print_r(":-)"); 
  • If you don't care about consecutive spaces, a similar option is ^\\w*(?: \\w*){0,3}$

  • Or, a more modern approach, with a lookahead (which is good for adding more constrains):
    ^(?![^ ]*(?: [^ ]*){4})[\\w ]*$

Either way, note that \\w includes underscores, you may want to replace it with something more suitable, for example [a-zA-Z\\d] or the Unicode aware [\\p{L}\\p{N}] .

I would do something like this:

if( count(explode(' ', $_POST['txt_username'])) <= 5 && preg_match('/^[\w ]+$/', $_POST['txt_username']) ){
  // do something
}

It's possible you could handle this all with a regular expression, but the solution would be overly complex. This should achieve the same result.


Example:

// press Ctrl-Enter to execute this code

$names = array(
    "hello world",         //valid
    "hello wo rl d",       //valid
    "h e l l o w o r l d", //invalid
    "hello123@@"           //invalid
);

function name_is_valid($name){
    return count(explode(' ', $name)) <= 5 && preg_match('/^[\w ]+$/', $name);
}

foreach($names as $n){
    echo sprintf("%s is %s\n", $n, name_is_valid($n)?"valid":"invalid");
}

/*
hello world is valid
hello wo rl d is valid
h e l l o w o r l d is invalid
hello123@@ is invalid
*/

see it here on tehplayground.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM