visual-craft / string-interpolator
PHP library which provides string interpolation (variable expansion) functionality
v1.0.0
2018-01-02 18:04 UTC
Requires
- php: ^5.5.0|^7.0
Requires (Dev)
- kahlan/kahlan: ^4.0
This package is auto-updated.
Last update: 2025-03-29 00:28:45 UTC
README
PHP library which provides string interpolation (variable expansion) functionality
Install
composer require visual-craft/string-interpolator
Usage
Instantiate interpolator object
use VisualCraft\StringInterpolator\StringInterpolator; $interpolator = new StringInterpolator();
String interpolation
$result = $interpolator->interpolate('Demonstration $var1 $var2.', [ 'var1' => 'of', 'var2' => 'interpolation', ]); // $result === "Demonstration of interpolation."
Variable name can be enclosed with '{' and '}' to separate from the rest of the string:
$result = $interpolator->interpolate('test${var1}test', [ 'var1' => '123', ]); // $result === "test123test"
'$var_name' can be escaped with '\':
$result = $interpolator->interpolate('$var1 \$var2', [ 'var1' => '123', ]); // $result === "123 $var2"
VisualCraft\StringInterpolator\MissingVariableException
will be thrown if variable is missing:
$result = $interpolator->interpolate('$var1 $var2', [ 'var1' => '123', ]); // PHP Fatal error: Uncaught VisualCraft\StringInterpolator\MissingVariableException: Missing variable 'var2'
Get variables names from subject
$result = $interpolator->getVariablesNames('Demonstration $var1 $var2.'); // $result === ['var1', 'var2']
Get variables counts from subject
$result = $interpolator->getVariablesCounts('Demonstration $var1 $var2. $var1'); // $result === ['var1' => 2, 'var2' => 1]
Tests
composer install --dev vendor/bin/kahlan
License
MIT