Check if String has only Integers separated by comma in PHP

后端 未结 3 990
眼角桃花
眼角桃花 2021-01-12 19:10

I am really empty at Regex side and that\'s why couldn\'t get how to make a Regex in PHP which checks if the string has this particular sequence of characters.



        
相关标签:
3条回答
  • 2021-01-12 19:20

    If you do not care about the format then you can just check for the characters:

    $regex = '/^[0-9,]+$/';
    if (preg_match($regex, $str) === 1) {
        echo 'Matches!';
    }
    

    You can also do it without using regular expressions:

    $str = str_replace(',', '', $str);
    if (ctype_digit($str)) {
        echo 'Matches!';
    }
    

    If you care about the format then something like this would work:

    $regex = '/^[0-9]+(?:,[0-9]+)*$/';
    if (preg_match($regex, $str) === 1) {
        echo 'Matches!';
    }
    
    0 讨论(0)
  • 2021-01-12 19:32

    Just for fun with no regex:

    var_dump(
        !array_diff($a = explode(',', $str), array_map('intval', $a))
    );
    
    0 讨论(0)
  • 2021-01-12 19:36

    You can use this regex:

    '/^\d+(?:,\d+)*$/'
    

    Code:

    $re = '/^\d+(?:,\d+)*$/';
    $str = '2323,321,329,34938,23123,54545,123123,312312'; 
    
    if ( preg_match($re, $str) )
        echo "correct format";
    else
        echo "incorrect format";
    
    0 讨论(0)
提交回复
热议问题