Helper for formatting strings with dynamic data
composer require smoren/string-formatter
composer install
./vendor/bin/codecept build
./vendor/bin/codecept run unit tests/unit
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.
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.
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.
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}.