Jump to content

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


LLLLLLL

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.

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.

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:

/^[a-z]+$/
Now just extend that to cover all your characters.
  • 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?

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.