PHP checks if a string contains max 30 letters / numbers in sequence with preg_match

I am stuck here and I cannot find any results for my question, maybe because English is not my first language.

I want to match strings that have a maximum of 30 letters / numbers in a sequence:

Is this possible with preg_match?

preg_match("/[^A-Za-z0-9](max 30 in a sequence)/", $string)

      

Strings:

$string = "1234567890123456789012345678901234567890"; // FALSE
$string = "sdfihsgbfsadiousdghiug"; // TRUE
$string = "cfgvsdfsdf786sdf78s9d8g7stdg87stdg78tsd7g0tsd9g7t"; // FALSE
$string = "65656.sdfsdf.sdfsdf"; // TRUE
$string = "ewrwet_t876534875634875687te8---7r9w358wt3587tw3587"; // TRUE
$string = "sd879dtg87dftg87dftg87ftg87tfg087tfgtdf8g7tdf87gt8t___454"; // FALSE

      

+3


source to share


3 answers


You might want to know if there are 30 or more of these characters:

preg_match("/[A-Za-z0-9]{30,}/", $string)

      

See matches in bold:

1234567890123456789012345678901234567890
sdfihsgbfsadiousdghiug
cfgvsdfsdf786sdf78s9d8g7stdg87stdg78tsd7g0tsd9g7t
65656.sdfsdf.sdfsdf
ewrwet_t876534875634875687te8 --- 7r9w358wt3587tw3587
sd879dtg87dftg87dftg87ftg87tfg087tfgtdf8g7tdf87gt8t ___ 454



http://regexr.com/3arj2

And then we deny the result:

preg_match("/[A-Za-z0-9]{30,}/", $string) === 0
// returns 0 if no match
// or FALSE if error

      

+5


source


If you don't want to match alphanumeric strings longer than 30 characters, you need to match a non-alphanumeric character at the end and beginning of the expression



preg_match("/[^A-Za-z0-9][A-Za-z0-9]{1,30}[^A-Za-z0-9]/", $string);

      

+2


source


Doesn't match your examples, your regex is wrong. You need ^

outside the character class, inside it means an exception. If nothing is entered, this should work. Unless changed 0

to a 1

.

preg_match("/^[A-Za-z0-9]{0,30}/", $string)

      

+1


source







All Articles