Reputation: 31
I am pretty familiar with PHP, but I am brand new with regular expressions in PHP. I am trying to figure out how to only allow a-z, A-Z, 0-9, :, ' (single quote), " " (double quote), +, -, ., (comma), &, !, *, (, and ).
I have found several working examples of what I am looking for EXCEPT how to allow the single quote and the double quote.
An Example of what I am looking for is: Hello, this is just an example of what I am looking for: "Hello World!".
I am trying to validate a textarea $_POST['suggestion'] using:
$errors = array();
if(!preg_match('insert regular expression',$_POST['suggestion'])){
$errors['suggestion2'] = "Invalid";
}
With everything I have tried, I always get:
An Example of what I am looking for is: Hello, this is just an example of what I am looking for: \"Hello Wolrd!\".
I don't understand why the \ are in front of the quotes?
Upvotes: 1
Views: 2054
Reputation: 626816
You can use the following regex:
[a-zA-Z0-9:'"+.,&!*()-]
Note that the hyphen -
is placed at the end position so as not to form a range (and it can match a literal -
). +
, *
, .
, (
and )
do not have to be escaped inside a character class. Generally, ^-]
should be escaped, but if they appear at the start of final position in the character class, they do not have to. \
must be escaped in the character class, but you are not allowing it.
Also, if you want to match chunks of allowed symbols, add a +
quantifier after the character class: [a-zA-Z0-9:'"+.,&!*()-]+
.
Sample PHP code:
$re = "/[a-zA-Z0-9:'\"+.,&!*()-]/";
$str = "a-zA-Z0-9:'\"+.,&!*()-";
preg_match_all($re, $str, $matches);
EDIT:
Since you updated the question, here is the information to turn off escaping double quotes in earlier PHP versions. As one of the options, you may go to .htaccess file and set php_flag magic_quotes_gpc Off
.
Upvotes: 5