php – How to make Regex that only accept numbers?

Question:

How do I use 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;
    }

   }
}

Answer:

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

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

Change it:

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

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

For:

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}$# which says the string must be exactly eleven digits long.

You can 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 there were two ifs, now the conditions were joined to say if the input (cpf) is valid or not.

The way the cpf is formatted has changed first the string is converted into an array separated by three characters each element ie there are four elements of length 3 and the last one as 2.

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

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);
}
Scroll to Top