$str = '111,222:'; $digits = '\d{1,3}'; $regex = "/((?:{$digits},{$digits})|):((?:{$digits},{$digits})|)?/"; if(preg_match($regex, $str, $matches)){ var_dump($matches); }else{ echo 'you fail'; }