Search code examples
phpregex

Check if String has only Integers separated by comma in PHP


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.

$str = '2323,321,329,34938,23123,54545,123123,312312';

Means to check if the string contains only Integers (Not decimal, no alphabats or anything else) separated by comma (,).


Solution

  • 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";
    

    RegEx Details:

    • ^: Start
    • \d+: Match 1+ digits
    • (?:,\d+)*: Match comma followed by 1+ digits in a non-capturing group. Repeat this group 0 more times.
    • $: End