Check if a string has only integers separated by comma in PHP

I am really empty on the side of Regex and why I could not get how to create a Regex in PHP that checks if a string has a specific character sequence.

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

Allows you to check whether a string contains only integers (not decimal, nor alphabets, or anything else), separated by a comma (,).

+4
source share
3 answers

You can use this regex:

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

The 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";
+5
source

Just for fun without regex:

var_dump(
    !array_diff($a = explode(',', $str), array_map('intval', $a))
);
+3
source

, :

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

, :

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

, - :

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

Source: https://habr.com/ru/post/1537422/


All Articles