Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Validate string characters are UK or US Keyboard characters

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

like image 589
Colin Hill Avatar asked Jan 06 '11 20:01

Colin Hill


2 Answers

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
}
like image 126
Felix Kling Avatar answered Nov 18 '22 23:11

Felix Kling


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);
}
like image 34
Richard Tuin Avatar answered Nov 18 '22 23:11

Richard Tuin