lacus / cpf-fmt
Utility function to format CPF (Brazilian personal ID)
Requires
- php: >=8.1
Requires (Dev)
- phpunit/phpunit: ^10.5
- spatie/phpunit-watcher: ~1.24
This package is auto-updated.
Last update: 2025-09-23 05:03:05 UTC
README
Utility function/class to format CPF (Brazilian ID document).
PHP Support
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:
- ⭐ Starring the repository
- 🤝 Contributing to the codebase
- 💡 Suggesting new features
- 🐛 Reporting bugs
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