lacus/cpf-fmt

Utility function to format CPF (Brazilian personal ID)

dev-main 2025-09-23 04:58 UTC

This package is auto-updated.

Last update: 2025-09-23 05:03:05 UTC


README

Packagist Version Packagist Downloads PHP Version Test Status Last Update Date Project License

Utility function/class to format CPF (Brazilian ID document).

PHP Support

PHP 8.1 PHP 8.2 PHP 8.3
Passing ✔ Passing ✔ Passing ✔

Installation

# using Composer
$ composer require lacus/cpf-fmt

Import

<?php
// Using class-based resource
use Lacus\CpfFmt\CpfFormatter;

// Or using function-based one
use function Lacus\CpfFmt\cpf_fmt;

Usage

Object-Oriented Usage

$formatter = new CpfFormatter();
$cpf = '47844241055';

echo $formatter->format($cpf);       // returns '478.442.410-55'

// With options
echo $formatter->format(
    $cpf,
    hidden: true,
    hiddenKey: '#',
    hiddenStart: 3,
    hiddenEnd: 10
);  // returns '478.###.###-##'

The options can be provided to the constructor or the format() method. If passed to the constructor, the options will be attached to the CpfFormatter instance. When passed to the format() method, it only applies the options to that specific call.

$cpf = '12345678910';
$formatter = new CpfFormatter(hidden: true);

echo $formatter->format($cpf);                  // '123.***.***-**'
echo $formatter->format($cpf, hidden: false);   // '123.456.789-10' merges the options to the instance's
echo $formatter->format($cpf);                  // '123.***.***-**' uses only the instance options

Imperative programming

The helper function cpf_fmt() is just a functional abstraction. Internally it creates an instance of CpfFormatter and calls the format() method right away.

$cpf = '47844241055';

echo cpf_fmt($cpf);       // returns '478.442.410-55'

echo cpf_fmt($cpf, hidden: true);     // returns '478.***.***-**'

echo cpf_fmt($cpf, dotKey: '', dashKey: '_');     // returns '478442410_55'

Formatting Options

Parameter Type Default Description
escape ?bool false Whether to HTML escape the result
hidden ?bool false Whether to hide digits with a mask
hiddenKey ?string '*' Character to replace hidden digits
hiddenStart ?int 3 Starting index for hidden range (0-10)
hiddenEnd ?int 10 Ending index for hidden range (0-10)
dotKey ?string '.' String to replace dot characters
dashKey ?string '-' String to replace dash character
onFail ?callable fn($v) => $v Fallback function for invalid input

Contribution & Support

We welcome contributions! Please see our Contributing Guidelines for details. But if you find this project helpful, please consider:

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

See CHANGELOG for a list of changes and version history.

Made with ❤️ by Lacus Solutions