Search code examples
phpstrpos

Detect Characters In Any Order


I'm sorting a username registration system, and part of our protocol is that users can only use A-Z, a-z, 0-9, _, ., and -. In addition, they can't have two punctuation marks in a row.

I'm trying to find an easier way to detect the punctuation other than just writing out the physical strings:

if (strpos($string, "..") !== false || strpos($string, "._") !== false || strpos($string, "-.") || strpos($string, ".-"))

(The above doesn't include all cases; Just showing a few for example)

Is there an easier way to check the string for a math of two specific characters in a row in any order?

Thanks!


Solution

  • Validate against allowed symbols:

    if (preg_match("/[^A-Za-z0-9.,_-]/", $string)){
         throw new Exception("Illegal characters in username");
    }
    

    Check if two ore more punctuation marks are next to each other:

    if (preg_match("/[.,_-]{2,}/", $string)){
         throw new Exception("Two or more nearby punctuation symbols are not allowed in username");
    }