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);
}
Have you tried
^[0-9]*$
?– Jefferson Quesado
tried this way and it didn’t work out $regular = "/ [0-9]+$/";
– sol25lua
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].
– Woss
Apparently it works, see this test: https://ideone.com/IglogT.
– UzumakiArtanis