Regex to allow A-Z, - and '

后端 未结 6 2034
情歌与酒
情歌与酒 2021-01-16 21:25

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

相关标签:
6条回答
  • 2021-01-16 21:42

    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.

    0 讨论(0)
  • 2021-01-16 21:46

    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

    0 讨论(0)
  • 2021-01-16 21:47
    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 -.

    0 讨论(0)
  • 2021-01-16 21:54

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

    0 讨论(0)
  • 2021-01-16 22:00
    if (preg_match("/^[a-zA-Z -]*$/", $firstname)) {
        // do something here
    }
    

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

    0 讨论(0)
  • 2021-01-16 22:06

    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>

    0 讨论(0)
提交回复
热议问题