Reputation: 2367
I have a simple registration script I'm practicing with and I was wondering how I could check for special characters and numbers. Basically, for the user name area, no special characters are allowed. For the first name , last name area, no special characters and numbers are allowed. Would this be a regex operation?
Upvotes: 2
Views: 10876
Reputation: 7575
When I post information to php from a form I like to use the ctype functions, its what they are for. http://php.net/manual/en/book.ctype.php
So if you wanted to a-zA-Z you could
if( !ctype_alpha( $str ) )
die( 'Invalid characters' );
Or if you wanted a-zA-Z0-9 you could
if( !ctype_alnum( $str ) )
die( 'Invalid characters' );
Upvotes: 7
Reputation: 206831
Don't try to reject stuff you don't want - you'll always find out later that users are much more imaginative than you.
Only accept what you know you can handle. If you only want latin letters and spaces, validate that that is the only thing you're getting with something like:
/^[0-9a-zA-Z ]+$/
Add only the characters you trust in there if I missed some.
Upvotes: 0
Reputation: 1636
$stringWithout = preg_replace('/[^a-zA-Z]/', '', $string);
$stringWith = $string;
if ($stringWith == $stringWithout) {
//string is clean
}
Something like this perhaps? If you replace every character but a-z and A-Z with nothing, and compare them, then if they are the same, you will know what they typed in has to be only characters like a-z and A-Z.
And yes, this uses a regex to replace the characters.
Upvotes: 2