Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

php

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."

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?

like image 601
user3838246 Avatar asked Jul 14 '14 19:07

user3838246


2 Answers

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

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

like image 73
Jeff Wurz Avatar answered Oct 18 '22 21:10

Jeff Wurz


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
like image 30
Erik Hendriks Avatar answered Oct 18 '22 23:10

Erik Hendriks