smoren / string-formatter
Helper for formatting strings
v2.0.0
2023-06-15 19:24 UTC
Requires
- php: >=7.2.0
- smoren/extended-exceptions: ^1.0
- smoren/schemator: ^2.1
Requires (Dev)
- codeception/codeception: ^4.2.1
- codeception/module-asserts: ^2.0
- php-coveralls/php-coveralls: ^2.0
- phpstan/phpstan: ^1.8
- squizlabs/php_codesniffer: 3.*
This package is auto-updated.
Last update: 2024-11-15 22:50:17 UTC
README
Helper for formatting strings with dynamic data
How to install to your project
composer require smoren/string-formatter
Unit testing
composer install
./vendor/bin/codecept build
./vendor/bin/codecept run unit tests/unit
Usage
Basic usage
use Smoren\StringFormatter\StringFormatter; $input = 'Hello, {name}! Your position is {position}.'; $params = ['name' => 'Anna', 'position' => 'programmer']; $result = StringFormatter::format($input, $params); echo $result; // Hello, Anna! Your position is programmer.
Usage with nested params
use Smoren\StringFormatter\StringFormatter; $input = 'Hello, {name}! Your position is {job.position}.'; $params = ['name' => 'Anna', 'job' => ['position' => 'programmer', 'salary' => 2000]]; $result = StringFormatter::format($input, $params); echo $result; // Hello, Anna! Your position is programmer.
Custom regexp usage
use Smoren\StringFormatter\StringFormatter; $input = 'Hello, %name%! Your position is %position%.'; $params = ['name' => 'Anna', 'position' => 'programmer']; $result = StringFormatter::format($input, $params, false, '/%([a-z]+)%/'); echo $result; // Hello, Anna! Your position is programmer.
Errors handling
use Smoren\StringFormatter\StringFormatter; use Smoren\StringFormatter\StringFormatterException; // Explicit mode $input = 'Hello, {name}! Your position is {position}.'; $params = ['name' => 'Anna']; try { StringFormatter::format($input, $params); } catch(StringFormatterException $e) { print_r($e->getData()); // ['position'] } // Silent mode $input = 'Hello, {name}! Your position is {position}.'; $params = ['name' => 'Anna']; $result = StringFormatter::format($input, $params, true); echo $result; // Hello, Anna! Your position is {position}. // Another variant of silent mode $input = 'Hello, {name}! Your position is {position}.'; $params = ['name' => 'Anna']; $result = StringFormatter::formatSilent($input, $params); echo $result; // Hello, Anna! Your position is {position}.