Jump to content

Allow only letters, numbers, dash, underscore, or space

Go to solution Solved by kicken,

Recommended Posts

Regex always kills me. I want a string to be only letters, numbers, dash, underscore, or space. 

	if ( !preg_match( $pattern, $str ) ){
		$err = 'Only letters, numbers, space, underscore and dash are allowed.';
		return $err

In this example, what is $pattern ? My best guess was...


$pattern = '/[^a-zA-Z0-9_-\s]+/';


... but it's not working.

Link to comment
Share on other sites

If you want the entire string then you have to make sure it matches every character from the beginning of the string to the end. That means ^ and $ anchors. Also, - in a character set can mean a range (like "A-Z") so you should either escape it or put it as the very first or very last character (where it couldn't possibly mean a range). Also also, \s is any whitespace so if you don't want tabs and newlines and such then you should put a literal space in there instead.

Link to comment
Share on other sites

  • Solution

The anchors go outside of the brackets. Putting them inside makes them additional valid characters rather than anchors. Within the brackets you just add the ranges/characters you want, keeping in mind the comments above.


After the brackets you need a repeater in order to allow multiple instances of the characters. + means one-or-more and works well.


for example:

Now just extend that to cover all your characters.
Link to comment
Share on other sites

  • 5 months later...

This thread is from last year and has been solved already. What's the point of digging it out?


This isn't really the perfect solution either:

  • You've forgotten the uppercase characters.
  • The underscore doesn't have any meaning, so no need to escape it.
  • A dash at the end of a character class doesn't have any meaning either, so again no need to escape it.
  • If you do use escaping, make it a double backslash, because the regex will be inside a PHP string.
  • What's the point of the parentheses?
  • The \s class contains tabs and newlines as well, which the OP did not want.
  • Why not use the \w class as suggested above?
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.

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.