validating a string [duplicate]

-3

I need to validate a string with php.

This string can only contain integer numbers, and will be separated by commas. It can count several numbers, and can not end or even begin with a comma.

Example of how it should be:

1 - 1,3,55,22,66,22,66 (the script does nothing because it is correct)

2 -, 23,32,2323,3 (displays message that is invalid)

3 - 23,32,2323,3, (displays message that is invalid)

5 - 23,32,2323,3, g4, f (displays message that is invalid)

I tried the following way:

$contas = "1,3,55,22,66,22,66";
if(preg_match("/^(\d+\s*,\s*)*\d+)*/",$contas)===true){
     echo "erro informações invalidas";
}

I tried this way but it did not work. Can anyone help me?

    
asked by anonymous 04.07.2016 / 20:39

1 answer

3

I used another approach. See if this function solves your problem:

function verificaContas($contas) {
  $arrContas = explode(",", $contas);
  $sucesso = true;
  foreach($arrContas as $conta) {
    if (!is_numeric($conta)){
        $sucesso = false;
        break;
    }
  }
  return $sucesso;
}

Run code: link

    
04.07.2016 / 21:32