Reputation: 4764
I would like to prevent new users from including apostophes, quotations and other special characters in their userids and passwords as I've found these can create unexpected problems down the road. Rather than anticipate every one of these problems, I'd rather just prohibit users from including those characters when signing up in the first place.
There are a lot of questions and stuff on the web in how to escape them to put them in the database but that is not the issue. I just want to throw an error msg that says enter something different.
I have tried:
$username = $_POST['username'];
if (preg_match ("/[&<>%\*\,\.\'\"]/i", $uid)) {
$strError="Your userid may not contain a special character. Please try again.";
}
but this is throwing an error No ending delimiter '''
found.
Would appreciate any suggestions.
Thanks.
Upvotes: 0
Views: 334
Reputation: 4618
may I suggest you not do that with preg_match ?
php has better functions for "sanitizing" strings - e.g. filter_var - check out FILTER_SANITIZE_STRING I would suggest this snippet
$usernameRaw = trim($_POST['username']);
$username = filter_var( $usernameRaw , FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
Upvotes: 0
Reputation: 945
I think you are going about this the wrong way. Instead of blacklisting special chars try whitelisting letters and digits e.g.
$username = $_POST['username'];
if (!preg_match('/^[\w\d]$/', $uid)) {
$strError="Your userid may not contain a special character. Please try again.";
}
to include asterisk and semicolon:
$username = $_POST['username'];
if (!preg_match('/^[\w\d\*;]$/', $uid)) {
$strError="Your userid may not contain a special character. Please try again.";
}
Upvotes: 1
Reputation: 1794
simplify it ...
<?php
$username = $_POST["username"];
if ( preg_match( "/^[A-Za-z0-9_]{3,20}$/", $username ) ) {
// username is valid
}
else {
// it contains special chars
}
?>
explaining regex
...
"/^[
A-Z # any uppercase letters
a-z # any lowercase letters
0-9 # any digits
_ # underscore
]{3,20} # minimum 3 and maximum 20 characters
$/x"
Upvotes: 1
Reputation: 5442
if (preg_match('/[^a-zA-Z]+/', $your_string, $matches))
{
echo 'Your userid may not contain a special character. Please try again.';
}
else
{
// No special characters found
}
Upvotes: 0
Reputation: 219884
The syntax highlighter shows you your obvious error: you have an extra '
on this line:
$username = $_POSt['username']';
should be
$username = $_POST['username'];
Upvotes: 0