Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression in PHP, with range of characters, but that excludes specific ones

I'm trying to create a regular expression with preg_match that can detect a string with the following requirements:

  1. Must contain at least 10 characters.
  2. There must be at least one of these: / (slash) . (dot) @ (arroba).
  3. Must not contain any of these letters: =, *, _, x, y, z

I think that I know how to achieve each requirement individually (maybe one of these is wrong), my problem is that I don't know how to concatenate all in a single expression.

  1. [a-ZA-Z]{10,}
  2. [/.@]
  3. [^=*_xyz]

The following scenarios must return 1 (or true).

$string1 = "Mega/lodon";  
$string2 = "Megalo.don";  
$string3 = "Me@galo/doing"; 

The following scenarios must return 0 (or false).

$string4 = "Meg@loz=on";  
$string5 = "Meglo*don";  
$string6 = "Megzlodonx";  
$string7 = "=egalodoing";

This is what I'm trying:

preg_match("/[a-zA-Z]{10,}.[\/.@]?.[^=*xyz]/", $string1);
like image 318
Ricardo Castañeda Avatar asked Dec 16 '25 12:12

Ricardo Castañeda


1 Answers

You can use:

^(?=.*[\/.@])[^=*_xyz]{10,}$

Here:

  • ^(?=.*[\/.@]) - checks that after beginning of string(^) somewhere there is any of symbols: /,.,@,
  • [^=*_xyz]{10,} - checks that your line at least 10 symbols and doesn't contain any of *,_,x,y,z,
  • $ - marker of the end of the string, so that no forbidden symbols could be matched after first 10 "good" ones.
like image 68
markalex Avatar answered Dec 19 '25 07:12

markalex