Respect\StringFormatter

February 9, 2026 · View on GitHub

Build Status Code Coverage Latest Stable Version Total Downloads License

A powerful and flexible PHP library for formatting and transforming strings.

Installation

composer require respect/string-formatter

Usage

You can use individual formatters directly or chain multiple formatters together using the FormatterBuilder:

echo f::create()
    ->mask('7-12')
    ->pattern('#### #### #### ####')
    ->format('1234123412341234');
// Output: 1234 12** **** 1234

Using Formatters as Modifiers

The PlaceholderFormatter allows you to use any formatter as a modifier within templates:

use Respect\StringFormatter\PlaceholderFormatter;

$formatter = new PlaceholderFormatter([
    'date' => '2024-01-15',
    'amount' => '1234.56',
    'phone' => '1234567890',
]);

echo $formatter->format('Date: {{date|date:Y/m/d}}, Amount: ${{amount|number:2}}, Phone: {{phone|pattern:(###) ###-####}}');
// Output: Date: 2024/01/15, Amount: \$1,234.56, Phone: (123) 456-7890

See the PlaceholderFormatter documentation and FormatterModifier documentation for more details.

Formatters

FormatterDescription
AreaFormatterMetric area promotion (mm², cm², m², a, ha, km²)
CreditCardFormatterCredit card number formatting with auto-detection
DateFormatterDate and time formatting with flexible parsing
ImperialAreaFormatterImperial area promotion (in², ft², yd², ac, mi²)
ImperialLengthFormatterImperial length promotion (in, ft, yd, mi)
ImperialMassFormatterImperial mass promotion (oz, lb, st, ton)
LowercaseFormatterConvert string to lowercase
MaskFormatterRange-based string masking with Unicode support
MassFormatterMetric mass promotion (mg, g, kg, t)
MetricFormatterMetric length promotion (mm, cm, m, km)
NumberFormatterNumber formatting with thousands and decimal separators
PatternFormatterPattern-based string filtering with placeholders
PlaceholderFormatterTemplate interpolation with placeholder replacement
SecureCreditCardFormatterMasked credit card formatting for secure display
TimeFormatterTime promotion (mil, c, dec, y, mo, w, d, h, min, s, ms, us, ns)
TrimFormatterRemove whitespace from string edges
UppercaseFormatterConvert string to uppercase

Contributing

Please see our Contributing Guide for information on how to contribute to this project.

License

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