Usage:
{{{
Text::insert(
'My name is {:name} and I am {:age} years old.', ['name' => 'Bob', 'age' => '65']
);
}}}
public static insert ( string $str, array $data, array $options = [] ) : string | ||
$str | string | A string containing variable place-holders. |
$data | array | A key, value array where each key stands for a place-holder variable name to be replaced with value. |
$options | array | Available options are: - `'before'`: The character or string in front of the name of the variable place-holder (defaults to `'{:'`). - `'after'`: The character or string after the name of the variable place-holder (defaults to `}`). - `'escape'`: The character or string used to escape the before character or string (defaults to `'\\'`). - `'clean'`: A boolean or array with instructions for `Text::clean()`. |
return | string |
/** * Ouputs the progress bar to STDOUT. */ protected function _progressBar() { if ($this->_current > $this->_total) { return; } $percent = $this->_current / $this->_total; $nb = $percent * $this->_size; $b = str_repeat($this->_chars['bar'], floor($nb)); $i = ''; if ($nb < $this->_size) { $i = str_pad($this->_chars['indicator'], $this->_size - strlen($b)); } $p = floor($percent * 100); $string = Text::insert($this->_format, compact('p', 'b', 'i')); $this->write("\r" . $string, $this->_color); }
it("inserts a variable as many time as it exists a placeholder", function () { $string = '{:a} {:b} {:a} {:a}'; $expected = '1 2 1 1'; $result = Text::insert($string, ['a' => 1, 'b' => 2]); $this->expect($result)->toBe($expected); }); it("inserts a variable with custom placeholder", function () { $string = '%a %b %a %a'; $expected = '1 2 1 1'; $result = Text::insert($string, ['a' => 1, 'b' => 2], ['before' => '%', 'after' => '']); $this->expect($result)->toBe($expected); }); it("escapes escaped placeholder", function () { $string = '{:a} {:b} \\{:a} {:a}'; $expected = '1 2 {:a} 1'; $result = Text::insert($string, ['a' => 1, 'b' => 2], ['escape' => '\\']); $this->expect($result)->toBe($expected); }); }); describe("::clean()", function () { it("cleans placeholder", function () { $result = Text::clean('{:incomplete}'); $this->expect($result)->toBe(''); }); it("cleans placeholder with a default string", function () { $result = Text::clean('{:incomplete}', ['replacement' => 'complete']); $this->expect($result)->toBe('complete'); }); it("cleans placeholder and adjacent spaces", function () { $result = Text::clean('{:a} 2 3'); $this->expect($result)->toBe('2 3');