正则表达式允许 A-Z, - 和 ' [英] Regex to allow A-Z, - and '
问题描述
我试图让这个正则表达式工作来验证名称字段以只允许 A-Z、' 和 -.
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 apostrophe.
if (preg_match("/[^a-zA-Z'-]+/",$firstname)) {
// do something
}
我希望它只允许 A-Z、-(破折号)和一个 '(撇号).它适用于 A-Z 和 - 但仍然不适用于 '
I would like it to only allow A-Z, - (dash) and an ' (apostrophe). It works for the A-Z and the - but still wont work for the '
有人可以举个例子吗?
谢谢
推荐答案
您的代码已经按照您的意愿行事:
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;
}
}
...打印:
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.
这篇关于正则表达式允许 A-Z, - 和 '的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!