验证字段的最佳正则表达式是什么?

Oni*_*ion 0 php regex user-generated-content

我在用户输入的字段上使用正则表达式,以确保它们输入了1到20个字符.

这是代码:

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

但是每当用户输入外来字符或MS Word中的特殊引号字符时(我无法将其粘贴到此处,它将其转换为正常引用!)正则表达式不会返回true,并且它显示错误.

我想知道什么是最好的正则表达式使用?

谢谢

sha*_*mar 6

如果您只想知道它是1到20个字符,为什么不使用strlen()

 $length = strlen($title);
 if($length >= 1 and $length <=20)
      echo "VALID";
 else
      echo "Invalid";
Run Code Online (Sandbox Code Playgroud)

[编辑]:检查aplhanumeric或puctuation:

如果您还想检查字符串是否包含可能导致问题的任何不可打印字符,请使用 ctype_graph()

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

[编辑2]:

如果您还想要   验证空格,只需使用:

if(ctype_graph(str_replace(' ', '',$title))
Run Code Online (Sandbox Code Playgroud)