skip to Main Content

My code:

preg_match("/^(?=.*[a-zA-Z].*[a-zA-Z].*[a-zA-Z])[0-9A-Za-z!@#$%^&_ -\']{3,48}$/", $hostname)

I want the site to accept user names like: John’s Pub. At the moment this kind of works because it allows for single quote (‘) but it also accepts ().

I have tried single quote on it’s own, with 1 and 2 but none of this works.

2

Answers


  1. You have several problems:

    1. Use case insensitive flag instead of [A-Za-z]
    2. You cannot put - in a []. block it means range! Escape it -.
    3. Don’t use \' it means a and ' which leads to nothing right!
    4. use w instead of 0-9A-Za-z. It’s simpler.

    Try this:

    preg_match("/^[w!@#$%^&_ -']{3,48}$/i", $hostname)
    

    If you want to allow character too, use this:

    preg_match("/^[w!@#$%^&_ -'\\]{3,48}$/i", $hostname)
    

    If you want to allow () characters too, use this:

    preg_match("/^[w!@#$%^&_ -'()]{3,48}$/i", $hostname)
    

    All Combined:

    preg_match("/^[w!@#$%^&_ -'()\\]{3,48}$/i", $hostname)
    
    Login or Signup to reply.
  2. To be specific to your problem you can try this:

    preg_match('/A(w*['()]*w*s*w*)+z/', $$hostname);
    

    Where:

    • A means Start of String
    • w means Any word character (letter, number, underscore)
    • * means 0 or more than 0 time(of prefix of *, here prefix is w)
    • ' means allow character ' similarly ( and ) is for defining allowed character
    • [] is group operator
    • s is for whitespace
    • z is for end of String

    Hope this will help

    Edit:
    You can try your custom regex here as well

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search