简体   繁体   中英

PHP - Regex : I need help to build regex according these rules

I need help building a regular expression for preg_match according these rules:

  1. first and last char- letter/digit only.
  2. empty space not allowed
  3. char can be only - letter/digit/'-'/'_'/'.'

Legal examples :

  1. b.t612_rt
  2. rut-be
  3. rut7565

Not legal example :

  1. .btr78; btr78- (first/last allowed chars)
  2. start end; star t end; (any empty space)
  3. tr$be; tr*rt; tr/tr ... (not allowed chars)

Edit: I remove 4 rule with neigbor chars '_'\\'-'\\'.'

please help me.

Thanks

Try this regular expression:

^[A-Za-z0-9]+([-_.][A-Za-z0-9]+)*$

This matches any sequence that starts with at least one letter or digit ( ^[A-Za-z0-9]+ ) that may be followed by zero or more sequences of one of - , _ , or . ( [-_.] ) that must be followed by at least one letter or digit ( [A-Za-z0-9]+ ).

Try this:

^[\p{L}\p{N}][\p{L}\p{N}_.-]*[\p{L}\p{N}]$

In PHP:

if (preg_match(
    '%^               # start of string
    [\p{L}\p{N}]      # letter or digit
    [\p{L}\p{N}_.-]*  # any number of letters/digits/-_.
    [\p{L}\p{N}]      # letter or digit
    $                 # end of the string.
    %xu', 
    $subject)) {
    # Successful match
} else {
    # Match attempt failed
}

Minimum string length: Two characters.

Well, for each of your rules:

  1. First and last letter/digit:

     ^[a-z0-9] 

    and

     [a-z0-9]$ 
  2. empty space not allowed (nothing is needed, since we're doing a positive match and don't allow any whitespace anywhere):

  3. Only letters/digits/-/_/.

     [a-z0-9_.-]* 
  4. No neighboring symbols:

     (?!.*[_.-][_.-]) 

So, all together:

/^[a-z0-9](?!.*[_.-][_.-])[a-z0-9_.-]*[a-z0-9]$/i

But with all regexes, there are multiple solutions, so try it out...

Edit: for your edit :

/^[a-z0-9][a-z0-9_.-]*[a-z0-9]$/i

You just remove the section for the rule you want to change/remote. it's that easy...

对于提供的示例,这似乎很好用: $patt = '/^[a-zA-Z0-9]+([-._][a-zA-Z0-9]+)*$/';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM