Replace PHP print correctly

Asked

Viewed 61 times

-1

I am a beginner in PHP and need to create a function that rewrites the text masking the CPF.

I, John Doe, Number 123.234.345/56, married to Beltrana, CPF 234.345.456/67, would like to request the registration of the property purchased Sicrano, CPF 345.456.567/78.

Turn

I, John Doe, CPF xxx, married to Beltrana, CPF xxx, would like to request the registration of the property purchased from Sicrano, CPF xxx.

I created the following function:

<?php

$texto = "Eu, Fulano, CPF 123.234.345/56, 
casado com Beltrana, CPF 234.345.456/67, 
gostaria de solicitar o registro do imóvel adquirido 
de Sicrano, CPF 345.456.567/78.";

function reescreverCpfs($texto)
{
    return preg_replace('/[^@\s]*.[^@\s]*\.[^@\s]*/',
        'xxx',
        $texto);
}
echo reescreverCpfs($texto);

But she’s printing the following:

I, John Doe, xxx married to Beltrana, xxx would like to request the registration of the property purchased of Sicrano, xxx

Could you help me?

1 answer

1

I don’t know if I understood the doubt correctly, but I think a better REGEX would be something like:

/\d{3}.\d{3}.\d{3}\/\d{2}/

This would be: {3 Digits}. {3 Digits}. {3 Digits}/{2 Digits}, which is the format of 123.234.345/56.


<?php

$texto = "Eu, Fulano, CPF 123.234.345/56, casado com Beltrana, CPF 234.345.456/67, gostaria de solicitar o registro do imóvel adquirido de Sicrano, CPF 345.456.567/78.";

function reescreverCpfs($texto) {
    // Só mudou o regex para o mencionado acima:
    return preg_replace('/\d{3}.\d{3}.\d{3}\/\d{2}/', 'xxx', $texto);
}

echo reescreverCpfs($texto);

Upshot:

Eu, Fulano, CPF xxx, casado com Beltrana, CPF xxx, gostaria de solicitar o registro do imóvel adquirido de Sicrano, CPF xxx.

Browser other questions tagged

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