Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

php - Need a regex that will check if the string only consist letters a-z and numbers and underscore(_) and hyphen(-)

I'm looking for a regex that will check if the string only consists of the letters a-z, numbers, underscore (_) and hyphen (-). I have tried this, but it does not work:

if (!preg_match('/^a-zA-Z0-9_-$/', $string)) {
  $reg_Error[] = 2;
}

Also, can I check the length with regex? If not, I will just do it with PHP.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to put your regex /^a-zA-Z0-9_-$/ in a character class /[...]/.
It means you can match any character in the character class. You should also specify a quantifier, because /^[a-zA-Z0-9_-]$/ will match only one character.

Examples:
/^[a-zA-Z0-9_-]+$/ with the + sign you match it one or more time
/^[a-zA-Z0-9_-]{1,}$/ the same as above
/^[a-zA-Z0-9_-]{10,20}$/ between 10 and 20 character long.
/^[a-zA-Z0-9_-]{15}$/ it has to be exactly 15 characters long. You can use it to check the string length.

You can also use the following keyword to make your regex easy to read:
/^[w-]+$/ which matches a word character (including underscore, letters and digits) or a dash, one or more time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...