dani
dani

Reputation: 11

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

Upvotes: 1

Views: 138

Answers (4)

Tim Pietzcker
Tim Pietzcker

Reputation: 336348

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.

Upvotes: 2

ircmaxell
ircmaxell

Reputation: 165251

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...

Upvotes: 1

mateusza
mateusza

Reputation: 5753

This seems to work fine for provided examples: $patt = '/^[a-zA-Z0-9]+([-._][a-zA-Z0-9]+)*$/';

Upvotes: 1

Gumbo
Gumbo

Reputation: 655479

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]+).

Upvotes: 3

Related Questions