Please help me create a regular expression so that if $ a does not match "n, n, n, n," then 1 is output.

In this case, my regular expression will be true even if $ a = 1.5, b, d, e. And you just need to have only numbers.

$a = '1,5,'; if(!preg_match('/([0-9]+)\,/i', $a)) { echo 1; } 

    1 answer 1

     $a = '1,5,'; if(!preg_match('/^(?:\d\,)+$/', $a)) { echo 1; } 

    ^ - beginning of line

    $ - end of line

    (?: \ d \,) - number and comma

    + - look for one or more times (in this case a number with a comma)

    If you need to search without a comma at the end:

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

    If a comma separated by a large number (132,564,234324):

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

    either suggested by @Palmervan :

     /^(?:\d\,?)+$/ 
    • /^(?:\d\,?)+$/ after the digit, the comma may not be. - Palmervan
    • From the conditions of the problem is not visible. Examples include: 'n, n, n, n,' and '1.5,' - Artem Ryzhov
    • What you wrote will even correspond to this: 1234,3425,3,4 It can be like this: / ^ (?: \ D \,?) + \ D? $ / - Artem Ryzhov
    • @Artem Ryzhov, thanks, helped :) - ModaL