Utility function/class to format CNPJ (Brazilian employer ID).
| Passing ✔ | Passing ✔ | Passing ✔ | Passing ✔ |
# using Composer
$ composer require lacus/cnpj-fmt<?php
// Using class-based resource
use Lacus\CnpjFmt\CnpjFormatter;
// Or using function-based one
use function Lacus\CnpjFmt\cnpj_fmt;$formatter = new CnpjFormatter();
$cnpj = '03603568000195';
echo $formatter->format($cnpj); // returns '03.603.568/0001-95'
// With options
echo $formatter->format(
$cnpj,
hidden: true,
hiddenKey: '#',
hiddenStart: 5,
hiddenEnd: 13
); // returns '03.603.###/####-##'The options can be provided to the constructor or the format() method. If passed to the constructor, the options will be attached to the CnpjFormatter instance. When passed to the format() method, it only applies the options to that specific call.
$cnpj = '03603568000195';
$formatter = new CnpjFormatter(hidden: true);
echo $formatter->format($cnpj); // '03.603.***/****-**'
echo $formatter->format($cnpj, hidden: false); // '03.603.568/0001-95' merges the options to the instance's
echo $formatter->format($cnpj); // '03.603.***/****-**' uses only the instance optionsThe helper function cnpj_fmt() is just a functional abstraction. Internally it creates an instance of CnpjFormatter and calls the format() method right away.
$cnpj = '03603568000195';
echo cnpj_fmt($cnpj); // returns '03.603.568/0001-95'
echo cnpj_fmt($cnpj, hidden: true); // returns '03.603.***/****-**'
echo cnpj_fmt($cnpj, dotKey: '', slashKey: '|', dashKey: '_'); // returns '03603568|0001_95'| 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 |
5 |
Starting index for hidden range (0-13) |
hiddenEnd |
?int |
13 |
Ending index for hidden range (0-13) |
dotKey |
?string |
'.' |
String to replace dot characters |
slashKey |
?string |
'/' |
String to replace slash character |
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
