Search code examples
phpregexlaravel-5whitelist

Regex - require some characters and allow only some additional?


I want to validate usernames in PHP and check them with a regular expression. They should contain at least 2 'real' characters, like A, Ä, s, 1 or 5, but some others like . or _ or a whitespace should be allowed , too. The position of the required characters does not matter.

This is what I had so far, and does unfortunately also allow ... as username:

preg_match('/^[\pL\pN\s-+_.]+$/u', $value)

I want to allow only certain characters. No <, or # for example. How can I do this?


Solution

  • Let's see...

    • At least two letters/numbers: ^(?:.*?[\p{L}\p{N}]){2}
    • Other characters allowed: ^[-+.\w ]+$

    Let's combine that together, and we get:

    ^(?=(?:.*?[\p{L}\p{N}]){2})[-+.\w ]+$
    

    I used a lookahead for the part that checks there are at least 2 required characters, and just put everything else in the main part of the pattern. Together, this lets you check two different conditions over the same input.