Utility function/class to format CPF (Brazilian ID document).
| Passing ✔ | Passing ✔ | Passing ✔ | Passing ✔ |
# using Composer
$ composer require lacus/cpf-fmt<?php
// Using class-based resource
use Lacus\CpfFmt\CpfFormatter;
// Or using function-based one
use function Lacus\CpfFmt\cpf_fmt;$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 optionsThe 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'| 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 |
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
This project is licensed under the MIT License - see the LICENSE file for details.
See CHANGELOG for a list of changes and version history.
Made with ❤️ by Lacus Solutions
