Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex to filter strings by length

Tags:

regex

php

I am trying to validate a input field with regex with this pattern [A-Za-z]{,10} I want it to only find a match if 10 or less chars was sent in the input field, the problem I get is that it will match all words that is less then 10 chars.

Is there a way to say if there is more then 10 chars in the input field come back as false, or is it just better to do a strlen with php?

like image 395
halliewuud Avatar asked Jul 15 '11 23:07

halliewuud


2 Answers

If you need to validate that it's alphabetic only, don't use strlen(). Instead, put boundaries (^$) on your regex:

/^[A-Za-z]{,10}$/
like image 179
Michael Berkowski Avatar answered Sep 23 '22 15:09

Michael Berkowski


There is an important syntax mistake being made here by the OP and all the current regex answers: When using the curly brace quantifier with PHP (PCRE), you need to specify the first number. (i.e. The expression: {,10} is NOT a valid quantifier!) Although the comma and second number are optional, the first number in a curly brace quantifier is required. Thus the expression should be specified like so:

if (preg_match('/^[A-Za-z]{0,10}$/', $text))
    // Valid input
else
    // Invalid input
like image 37
ridgerunner Avatar answered Sep 24 '22 15:09

ridgerunner