Hello forums!!
I would like to know the regex for the following:
input text can contain

alphanumeric characters along with underscore and space

for example: "this is user_name"
i used the following:

/^[a-zA-Z0-9 _]+$/

this works but not perfectly because when the only space bar is pressed it takes the value, i want to prevent this, space should be @ the beginning, what will be the regex for this ?
Thanks in advance to all of you

    So a name must begin with an alphanum character or underscore, but can also contain spaces? Try this:

    if(!preg_match('/^[a-z0-9_][a-z0-9_ ]*$/i', $text)) {
        die('Bad value.');
    } else {
        // ...
    }

      Another option would be to [man]trim/man the input value before checking it (I almost always do this just to get rid of needless leading or trailing white-space):

      $text = trim($_POST['text']);
      if(preg_match('/[^\w ]/', $text))   // "\w" is "word characters" == [A-Za-z0-9_]
      {
         // invalid input
      }
      
        Write a Reply...