I am trying to get this Regex to work to validate a Name field to only allow A-Z, \' and -.
So far I am using this which is working fine apart from it wont allow an
Your code already does what you want it to:
<?php
$data = array(
// Valid
'Jim',
'John',
"O'Toole",
'one-two',
"Daniel'Blackmore",
// Invalid
' Jim',
'abc123',
'$@#$%@#$%&*(*&){}//;;',
);
foreach($data as $firstname){
if( preg_match("/[^a-zA-Z'-]+/",$firstname) ){
echo 'Invalid: ' . $firstname . PHP_EOL;
}else{
echo 'Valid: ' . $firstname . PHP_EOL;
}
}
... prints:
Valid: Jim
Valid: John
Valid: O'Toole
Valid: one-two
Valid: Daniel'Blackmore
Invalid: Jim
Invalid: abc123
Invalid: $@#$%@#$%&*(*&){}//;;
The single quote does not have any special meaning in regular expressions so it needs no special treatment. The minus sign (-), when inside [], means range; if you need a literal - it has to be the first or last character, as in your code.
Said that, the error (if any) is somewhere else.
From what I see. Following Regex should work fine:
if (preg_match("/^[A-Z\'\-]+$/",$firstname)) {
// do something
}
Here I have escaped both apostrophe and dash. I have tested this in an online Regex tester and works just fine.
Give it a try
if (preg_match("/^[A-Z'-]+$/",$firstname)) {
// do something
}
The caret ^ inside a character class [] will negate the match. The way you have it, it means if the $firstname contains characters other than a-z, A-Z, ', and -.
"/[^a-zA-Z'-]+/" actually matches everything but a-zA-z'-, if you put the ^ in to indicate the start-of-string, you should put it outside the brackets.
Also, the '- part of your expression is possibly being interpreted as a range, so you should escape the - as @Tom answered or escape the , as someone else answered
if (preg_match("/^[a-zA-Z -]*$/", $firstname)) {
// do something here
}
I have used this, This will work fine. Use It.
Your regexp should look like this:
preg_match("/^[A-Z\'-]+$/",$firstname);
maches: AB A-B AB-'
does not match: Ab a-B AB# <empty string>