PHP 字母和空格仅验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15346284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:04:52  来源:igfitidea点击:

PHP letters and spaces only validation

phpformsvalidation

提问by Andy Buckle

I'm validating my contact form using PHP and I've used the following code:

我正在使用 PHP 验证我的联系表单,并且使用了以下代码:

if (ctype_alpha($name) === false) {
            $errors[] = 'Name must only contain letters!';
}

This code is works fine, but it over validates and doesn't allow spaces. I've tried ctype_alpha_sand that comes up with a fatal error.

这段代码工作正常,但它过度验证并且不允许空格。我试过了ctype_alpha_s,但出现了致命错误。

Any help would be greatly appreciated

任何帮助将不胜感激

回答by Martin

Regex is overkill and will perform worse for such a simple task, consider using native string functions:

正则表达式是矫枉过正,对于这样一个简单的任务会表现得更糟,考虑使用原生字符串函数:

if (ctype_alpha(str_replace(' ', '', $name)) === false) {
  $errors[] = 'Name must contain letters and spaces only';
}

This will strip spaces prior to running the alpha check. If tabs and new lines are an issue you could consider using this instead:

这将在运行 alpha 检查之前去除空格。如果制表符和新行是一个问题,您可以考虑使用它:

str_replace(array("\n", "\t", ' '), '', $name);

回答by V_K

ctype_alpha only checks for the letters [A-Za-z]

ctype_alpha 只检查字母 [A-Za-z]

If you want to use it for your purpose, first u will have to remove the spaces from your string and then apply ctype_alpha.

如果您想将它用于您的目的,首先您必须从字符串中删除空格,然后应用 ctype_alpha。

But I would go for preg_match to check for validation. You can do something like this.

但我会去 preg_match 来检查验证。你可以做这样的事情。

if ( !preg_match ("/^[a-zA-Z\s]+$/",$name)) {
   $errors[] = "Name must only contain letters!";
} 

回答by Jinia

if (ctype_alpha(str_replace(' ', '', $name)) === false)  {
  $errors[] = 'Name must contain letters and spaces only';
}

回答by Epiphany

One for the UTF-8 world that will match spaces and letters from any language.

一种用于 UTF-8 世界,可以匹配来自任何语言的空格和字母。

if (!preg_match('/^[\p{L} ]+$/u', $name)){
  $errors[] = 'Name must contain letters and spaces only!';
}

Explanation:

解释:

  • [] => character class definition
  • p{L} => matches any kind of letter character from any language
  • Space after the p{L} => matches spaces
  • + => Quantifier — matches between one to unlimited times (greedy)
  • /u => Unicode modifier. Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters
  • [] => 字符类定义
  • p{L} => 匹配来自任何语言的任何类型的字母字符
  • p{L} => 后的空格匹配空格
  • + => 量词 — 匹配一次到无限次(贪婪)
  • /u => Unicode 修饰符。模式字符串被视为 UTF-16。还会导致转义序列匹配 unicode 字符

This will also match names like Bj?rk Guemundsdóttiras noted in a comment by Anthony Hatzopoulos above.

这也将匹配Bj?rk Guemundsdóttir 之类的名称,如上面 Anthony Hatzopoulos 的评论中所述。