Reputation: 2327
I'm having a hard time putting the correct expression together, so that it rejects everything except letters, periods, apostrophes, spaces and hyphens.
So far this works for everything except the apostrophe, which I've tried to escape with both single and double "\" to no avail.
if(!preg_match("/^[a-zA-Z'. -]+$/",$_POST['name']))
{
$error_name="The name you entered is invalid.";
}
//obrien - pass
//o'brien - fail
//Dr. OBrien - pass
//Dr. O'Brien - fail
This works perfectly except that no apostrophe clears it.
Upvotes: 3
Views: 4714
Reputation: 31
Here's an amazing one I was able to come up with, I think it should be able to work with most names that have both hypens, apostrophes, spaces and so on.
if(!preg_match('/^([a-zA-Z]+[\'-]?[a-zA-Z]+[ ]?)+$/', $string))
Upvotes: 3
Reputation: 2327
The problem ended up being that in the php.ini that I can't access on my godaddy account, addslashes must be enabled. The following made it work. Thank you to Sergey for leading me to think about what the server might be doing to the posted data.
if(!preg_match("/^[a-zA-Z'. -]+$/", stripslashes($_POST['name']))
{
whatever error message
}
Upvotes: 3
Reputation: 1693
I think it happens because you are trying to check url-encoded string. Replace $_POST['name']
with urldecode($_POST['name'])
. The apostrophe at this stage looks like %27
, so O'Brien in $_POST['name'] is O%27Brien and it will not pass your regular expression.
Edit: Also, maybe it is another type of apostrophe you have entered in the form: ’
.
As a result:
if(!preg_match("/^[a-zA-Z’'. -]+$/",urldecode($_POST['name'])) {
$error_name="The name you entered is invalid.";
}
Upvotes: 2