Jump to content

Regex for alphanumeric's and spaces


.Stealth

Recommended Posts

Having some trouble with regex as usual, why do they make it so hard? :o

 

All i want is to check that a string has only text, numbers and spaces in it, that is all. It can contain spaces anywhere at all and as many of them. All the examples I've seen just show how to do one space at the beginning/end, not how to do as many as you want. I've tried all sorts of things but most just completely break it.

 

Here's what I've got:

 

function alphaNumTextCheck($string){
   if(preg_match('/[^a-z0-9]/', $string)){
      return TRUE;
   }
   else{
      return FALSE;
   }
}

 

 

That only checks for text and numbers, if i add a space into the string it comes back FALSE.

 

Can anybody help? Thanks.

Link to comment
Share on other sites

You have your True/False backwards. That regex tests to see if there are any characters NOT in the list specified. Since you don't want those characters you should be returning false. Adding a space in the character list works fine for me. Also, assuming you want to allow capital letters you need to add A-Z, or better yet, just make the regex case insensitive using the "i" parameter.

 

Lastly, no need to create an If/Else to return True/False since the preg_match will do that for you:

 

function alphaNumTextCheck($string)
{
    return (!preg_match('/[^a-z0-9 ]/i', $string));
}

alphaNumTextCheck('word'); //Returns true
alphaNumTextCheck('word123'); //Returns true
alphaNumTextCheck(' word 123 '); //Returns true
alphaNumTextCheck('word#123'); //Returns false
alphaNumTextCheck('word:123'); //Returns false

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.