How to make Regex accept only numbers?

Asked

Viewed 2,759 times

3

How do I use the preg_match that only accept numbers? And that these numbers can also start with zero?

function formatacao_cpf_func(){

    $regular = "/^[0-9]*$/";

    if(preg_match($regular, $this->cpf)){

    if(!is_numeric($this->cpf)){
        echo "O campo CPF só poderá conter Números";
        die;
    }

    if(strlen($this->cpf) > 11 || strlen($this->cpf) < 11 ){
        echo "Por favor informe o CPF com 11 digitos Válidos";
        $tamanho = strlen($this->cpf);
        echo $tamanho;
        die;
    }

    if(strlen($this->cpf) == 11){
       echo "CPF foi digitado corretamente </br>";
       $formatando_cpf_func = substr($this->cpf, 0, 3) . '.' . substr($this->cpf, 3, 3) . 
            '.' . substr($this->cpf, 6, 3) . '-' . substr($this->cpf, 9, 2);
       echo $formatando_cpf_func;
    }

   }
}
  • Have you tried ^[0-9]*$?

  • tried this way and it didn’t work out $regular = "/ [0-9]+$/";

  • 5

    And what is the content of string and what is the expected result? Put this together with your code in the question, using the [Edit button].

  • Apparently it works, see this test: https://ideone.com/IglogT.

2 answers

2

Can use ctype_digit() to check if string contains only numbers. is_numeric() accepts fractionated numbers, negatives and plus sign.

var_dump(is_numeric(-1.33)); //true
var_dump(is_numeric(+1.33)); //true

Change:

$regular = "/^[0-9]*$/";
if(preg_match($regular, $this->cpf)){

if(!is_numeric($this->cpf)){
    echo "O campo CPF só poderá conter Números";
    die;
}

To:

if(!ctype_digit("$this->cpf")){
   echo "O campo CPF só poderá conter Números";
   die;
}

If you really want to use regex, you can use #^\d{11}$# that says the string must have exactly eleven digits.

It is possible to refactor this function to:

function formatacao_cpf_func(){

    $tamanhoCPF = strlen($this->cpf);

    if(!ctype_digit("$this->cpf") || $tamanhoCPF != 11) die('O campo CPF é inválido');


    echo "CPF foi digitado corretamente </br>";
    $arr = str_split($str, 3);
    printf('%s.%s.%s-%s', ...$arr);
}

Basically where they had two if, now the conditions have been put together to tell whether the input (Cpf) is valid or not.

The way Cpf is formatted first the string is converted into an array separated by three caracateres each element ie are four elements of length 3 and the last as 2.

printf() or sprintf() assemble a mask based on the format. Remembering that the operator ... (Ellipsis) only works from php5.6 forward in previous versions it is necessary to specify the array indexes or use the function vprintf().

In the regex version the size is already validated along with the numeric characters.

function formatacao_cpf_func($cpf){

    $regex = '#^\d{11}$#';
    if(!preg_match($regex, $cpf)) die('O campo CPF é inválido');

    echo "CPF foi digitado corretamente </br>";
    $arr = str_split($cpf, 3);
    printf('%s.%s.%s-%s', ...$arr);
}
  • Do you have a problem with the answer?

  • The people here are demanding kkk, maybe it’s because he wants a REGEX and his answer did not solve the problem the way he wanted.

  • @Guilhermebiancardi, I particularly did not see how this response is of poor quality. The use of regex for this case can be a sign of if use a tank to open coconuts... then alternative answers that do not use tanks of war should be accepted. After all, that particular question did not indicate to be a kind of code-golf to be programmed within restricted programming parameters

  • @Jeffersonquesado I’m just saying what I think... if I need a REGEX for example why will I use "is_numeric()" by what I know 000.000.000-00 would return false... already with the REGEX... And I don’t think the REGEX is a tank of war opening a coconut... if the guy used a "explode()" with a "for()" then I’d say he’s using a tank of war to open a coconut.

  • 1

    @Guilhermebiancardi does not need regex to solve this problem but if you want you can use :)

  • @rray, ratifying this his last comment: I would use regex for addiction, I live by injecting coffee and regex in the vein. But I know that it is a solution Overkill for that case, given the input.

  • internally the ctype_digit would not be a for running through each character? I don’t think there would be much difference between the regex engine shown and the ctype. cc @jeffersonquesado

  • @Guilhermelautert I don’t know how it works ctype_digit() internally :P. At least in the tests I did ctype and regex the ctype_ was slightly better.

  • @interesting rray, and even understand this little difference.

  • 1

    @Guilhermelautert the advantage of the same regex is to validate the two criteria at the same time.

Show 5 more comments

0

 $regular = "#^\d+$#";

 if(preg_match($regular, $this->cpf)){
   // somente numero;

   if(strlen($this->cpf) == 11){
     // Uma ajuda extra com regEx para formatar o cpf
     $formatando_cpf_func = preg_replace("#(\d{3})(\d{3})(\d{3})(\d{2})#", "$1.$2.$3-$4", $this->cpf);
     echo "CPF foi digitado corretamente </br> $formatando_cpf_func";
   } else {
     echo "Por favor informe o CPF com 11 digitos Válidos";
     $tamanho = strlen($this->cpf);
     echo $tamanho;
     die;
   }
 } else {
   // if(!is_numeric($this->cpf)) <-- remover essa validação, não é necessária, já que foi feita com regex
   echo "O campo CPF só poderá conter Números";
   die;
 }
  • Could explain, with text, your solution, making clear what are the differences between your code and the question and what were the problems of the AP code?

Browser other questions tagged

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