php 正则表达式只允许字母、数字、空格、逗号、句点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24744375/
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 17:26:59  来源:igfitidea点击:

Regex for only allowing letters, numbers, space, commas, periods?

phpregex

提问by user3838246

I am clueless with regex as it is complicated for me. I am working with a program that limits input from users based on a regex. I am currently after a regex that will only let the user input:

我对正则表达式一无所知,因为它对我来说很复杂。我正在使用一个基于正则表达式限制用户输入的程序。我目前正在使用一个只会让用户输入的正则表达式:

A-Z and a-z
0-9
.
,
!
?

So basically anything in a typical paragraph or web article.

所以基本上是典型段落或网络文章中的任何内容。

The program states "Enter a regular expression which entered text must match (evaluated with preg_match, using s and i flags) for it to be valid."

程序声明“输入一个正则表达式,输入的文本必须匹配(使用 preg_match 评估,使用 s 和 i 标志)才能使其有效。”

I have tried this regex with no success and I am currently searching for others to try.

我已经尝试过这个正则表达式但没有成功,我目前正在寻找其他人来尝试。

 '/^[a-zA-Z0-9,.!? ]*$/'

It should allow a simple sentence such as

它应该允许一个简单的句子,例如

"HI my name is John! I like to eat apples, oranges, and grapes. Will you eat with me?

“嗨,我叫约翰!我喜欢吃苹果、橙子和葡萄。你愿意和我一起吃吗?

回答by Jeff Wurz

Debuggex example

Debuggex 示例

^[a-zA-Z0-9,.!? ]*$

^[a-zA-Z0-9,.!? ]*$

is what the regex is, it works, see example website to test regex.

正则表达式是什么,它可以工作,请参阅示例网站来测试正则表达式。

回答by Erik Hendriks

You could also use '/^[\w .,!?]+$/'

你也可以使用 '/^[\w .,!?]+$/'

The alphanumeric \w metacharacter is equivalent to the character range [A-Za-z0-9_]

字母数字 \w 元字符等效于字符范围 [A-Za-z0-9_]

eg:

例如:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["message"])) {
    $messageErr = "Message cant be empty";
  } elseif (preg_match('/^[\w .,!?()]+$/', $message) === false){
    $messageErr = "Only aA-zZ09.,!?_ are allowed";
  } else {
    $message = data($_POST["message"]);
  }
}
function data($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
# Do something with $message

回答by oliver_48

You don't even need a-z or 0-9. "[\w,.!?]"should work.

你甚至不需要 az 或 0-9。 "[\w,.!?]"应该管用。