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

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


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

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


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

The alphanumeric \w metacharacter is equivalent to the character range [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

Tags:

Php

Regex