CPF Regex with Laravel

Asked

Viewed 753 times

1

The system where I am doing maintenance has Cpfs registered in two ways, with and without score, due to a bad development start that did not impose a standard. The problem is that the CPF cannot repeat itself, and when the user types a CPF without punctuation, if it is already recorded with punctuation, it will indicate that it is a new CPF.

I believe I should use regex to compare the two, but I don’t know how to apply it to the query. Below is the consultation held:

$customer = Customer::where('cpf', $valor)->first();
  • 6

    Wouldn’t it be better to fit all records to the correct standard?

3 answers

5


The biggest solution would be to normalize all values in the column without formatting. The provisional way is to treat the comparison values in the same way or by removing the formatting.

You can write a query in Mysql with replace()

SELECT replace(replace('123.456.789-10', '.', ''), '-', '')

The complete solution should be something like:

$valor = str_replace(array('.', '-'), '', $valor);
$customer = Customer::where("REPLACE(REPLACE(cpf, '.', ''),'-', '')", $valor)->first();
  • SELECT X_REG_REPLACE('123.456.789-10', '[^0-9]', '');, I don’t have Mysql here, if you want to test.

  • I agree, but the company is not allowing me to normalize the bank, because these data refer to another internal system of theirs, for me to normalize would have to normalize in the other system, which is extremely bureaucratic. I’ll test this search here and tell you how

  • I’ll see to that too William

  • @Guilhermelautert Mysql has no function ready to replace based on regex only searches. mariadb has regexp_replace

  • @Isaiaslima If the query is slow and possible create a new column cpf_limpo which stores Cpf without formatting so always use it in the searches (to recover Cpf compatible with other systems). Don’t forget to create a unique index.

  • 1

    @rray Mysql is the PHP of SGBS. A garbage :/

Show 1 more comment

2

In PHP you can try Regex replace this way:

$cpf = '12345678968';
$cpf_maskered = preg_replace('/(\d{3})(\d{3})(\d{3})(\d{2})/','$1.$2.$3-$4', $cpf);
echo $cpf_maskered;

If the CPF already contains dots and dashes, it will be the same.

1

  • The worst is when the CPF is saved with punctuation and receives a scoreless value to compare (since they are not allowing me to change the validation of the field, I do not know why, since it would solve everything), in this case it would not work with str_replace

Browser other questions tagged

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