phpregexuser-generated-content

What's the best regex for validating a field?


I use a regular expression to on a user-inputted field to make sure that they have entered between 1 and 20 characters.

Here's the code:

$post_validations = array("title" => '/^[[:alnum:][:punct:][:space:]]{1,100}$/');

But whenever a user enters a foreign character, or a special quote character from MS Word (I can't paste it into here, it converts it to a normal quote!) the regex doesn't return true, and it shows an error.

I wondered what would be the best regex to use?

Thanks


Solution

  • If all you want is know that it is between 1 and 20 characters, why not use strlen() ?

     $length = strlen($title);
     if($length >= 1 and $length <=20)
          echo "VALID";
     else
          echo "Invalid";
    

    [EDIT]: Checking whether aplhanumeric or puctuation:

    And if you also want to check whether the string contains any non-printable characters that may cause problem, just use ctype_graph()

     if(ctype_graph ($title))
          echo "Only alphanumeric or punctuation";
     else
          echo "Invalid non-printable characters found";
    

    [EDIT 2]:

    If you also want the spaces   to be validated, just use this:

    if(ctype_graph(str_replace(' ', '',$title))