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
https://forums.phpfreaks.com/topic/201395-regex-for-alphanumerics-and-spaces/
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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.