validate comma separated list using regex

前端 未结 4 947
囚心锁ツ
囚心锁ツ 2021-01-17 01:23

I want to validate that the user has entered a comma separated list of words only using regex, will this work/is there a better way:

 $match = \"#^([^0-9 A-z         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-17 02:04

    I don't know what the separate values should look like, but perhaps this is something that can help you:

    $value = '[0-9 A-Z]+';
    $match = "~^$value(,$value)*$~i";
    

    When you know what your values should look like you can change $value.


    Update

    Taken this comment from the question

    I was trying to disallow 0-9 but allow a-Z, because, as I said it should be a list of words only, no spaces, just a list of single words.

    Just change $value

    $value = '[A-Z]+';
    

    Note, that I use the i-modifier in $match, that will include all lowercase letters too.


    However, "real" csv allows a little bit more than this, for example you can put quotes around every value. I would recommend that you parse the line and then test every single value

    $values = str_getcsv($line);
    $valid = true;
    foreach ($values as $value) {
      $valid = $valid && isValid($value);
    }
    

    str_getcsv()

提交回复
热议问题