开发者

Regex to allow A-Z, - and '

开发者 https://www.devze.com 2023-04-04 09:57 出处:网络
I am trying to 开发者_如何学JAVAget this Regex to work to validate a Name field to only allow A-Z, \' and -.

I am trying to 开发者_如何学JAVAget 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
        }

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 '

Could someone please provide an example?

Thanks


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 -.


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.


"/[^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


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


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>


if (preg_match("/^[a-zA-Z -]*$/", $firstname)) {
    // do something here
}

I have used this, This will work fine. Use It.

0

精彩评论

暂无评论...
验证码 换一张
取 消