kahlan\util\Text::insert PHP Method

insert() public static method

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
    public static function insert($str, $data, $options = [])
    {
        $options += ['before' => '{:', 'after' => '}', 'escape' => '\\', 'clean' => false];
        extract($options);
        $begin = $escape ? '(?<!' . preg_quote($escape) . ')' . preg_quote($before) : preg_quote($before);
        $end = preg_quote($options['after']);
        foreach ($data as $placeholder => $val) {
            $val = is_array($val) || is_resource($val) || $val instanceof Closure ? '' : $val;
            $val = is_object($val) && !method_exists($val, '__toString') ? '' : (string) $val;
            $str = preg_replace('/' . $begin . $placeholder . $end . '/', $val, $str);
        }
        if ($escape) {
            $str = preg_replace('/' . preg_quote($escape) . preg_quote($before) . '/', $before, $str);
        }
        return $options['clean'] ? static::clean($str, $options) : $str;
    }

Usage Example

Example #1
0
 /**
  * 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);
 }
All Usage Examples Of kahlan\util\Text::insert