Reputation: 1315
I have a quick regex question that I figured someone might know off the top of their head. What would the regex be for CakePHP's validation be if I only want to allow upper/lower alphanumber, spaces, punctuation, and quotes? This is what I have, but it's off:
'rule' => array('custom', '/[a-z0-9\x20\x21\x2E\x3A\x3B\x3F\x2C\x27\x22]{0,600}/i'),
From what I get, the a-z0-9 covers alphanumeric, but shouldn't the \xXX cover the punctuation with the ASCII hex codes? And then the {0,600] means a length of 0-600 characters, and i means upper and lower. What am I missing?
For example: valid: This is a "valid text", which contains ' and punctuation!
invalid: This is an obvious XSS attempt
Upvotes: 3
Views: 3518
Reputation: 5768
^([\d\w\s?!\.;:,'"\/\[\]\(\)=\+-]*)$
should work? You should provide examples of what texts you consider to be valid and which are invalid.
preg_match('/^([\d\w\s?!\.;:,'"\/\[\]\(\)=\+-]*)$/', $string);
Upvotes: 3
Reputation: 11
As long as you know you want it to be ASCII, just use the character ranges
$input = "this is a \n string\n";
echo preg_match("/^[ -~]{0,600}$/", $input); // output is 0 (false)
$input = "this is a string";
echo preg_match("/^[ -~]{0,600}$/", $input); // output is 1 (true)
Whenever I deal with ASCII I find the specific ranges much easier. So basically you want the start of the string to be anything within a space and ~, which are all visible characters. And then you have a 0-600 character limit, and $ signifies the end of the string
Upvotes: 1