validating a string

Asked

Viewed 44 times

-3

People need to validate a string with php.

This string can contain only integer numbers, and will be separated by commas. She can count multiple numbers, and she can’t finish and she can’t start 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 it this 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 it but it didn’t work. Someone can help me?

  • 4

    This question is not the same as http://answall.com/questions/138656/verifi-uma-string-comphp?

1 answer

3


I took a different 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;
}

Code executed: http://ideone.com/2ClRw9

Browser other questions tagged

You are not signed in. Login or sign up in order to post.