What is the easiest or best way in PHP to validate true or false that a string开发者_开发知识库 only contains characters that can be typed using a standard US or UK keyboard with the keyboard language set to UK or US English?
To be a little more specific, I mean using a single key depression with or without using the shift key.
I think the characters are the following. 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()_-+={[}]|\:;"'<,>.?/£ and Space
You can cover every ASCII character by [ -~]
(i.e. range from space to tilde). Then just add £
too and there you go (you might need to add other characters as well, such as ±
and §
, but for that, have a look at the US and UK keyboard layouts).
Something like:
if(preg_match('#^[ -~£±§]*$#', $string)) {
// valid
}
The following regular expression may be of use for you:
/^([a-zA-Z0-9!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~\t ])*$/m
Use this as:
$result = (bool)preg_match('/^([a-zA-Z0-9!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~\t ])*$/m', $input);
Or create a reusable function from this code:
function testUsUkKeyboard($input)
{
return (bool)preg_match('/^([a-zA-Z0-9!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~\t ])*$/m', $input);
}
The easier way to check is to check if chars exist rather then they do not, so first you would need a list of chars that do not exists, you can get these from the ascii range 128 - 255 where as 0 - 127 is the regular key set.
Tio create the invalid array uou can do:
$chars = range(128,255);
The above array would contain all the chars in the table below:
then you should check agains the string in question, people say use regex, but i dont really think thats needed
$string = "testing a plain string";
for($s=0;$s<strlen($string);$s++)
{
if(in_array(ord($string[$s]),$chars))
{
//Invalid
}
}
精彩评论