Replaces variable placeholders inside a string with any given data. Each key
in the `$data` array corresponds to a variable placeholder name in `$str`.
Usage:
{{{
String::insert(
'My name is {:name} and I am {:age} years old.',
array('name' => 'Bob', 'age' => '65')
); // returns 'My name is Bob and I am 65 years old.'
}}}
Parameters
- string $str A string containing variable place-holders.
- array $data A key, value array where each key stands for a place-holder variable name to be replaced with value.
- array $options Available options are: - `'after'`: The character or string after the name of the variable place-holder (defaults to `}`). - `'before'`: The character or string in front of the name of the variable place-holder (defaults to `'{:'`). - `'clean'`: A boolean or array with instructions for `String::clean()`. - `'escape'`: The character or string used to escape the before character or string (defaults to `'\'`). - `'format'`: A regular expression to use for matching variable place-holders (defaults to `'/(?<!\\)\:%s/'`. Please note that this option takes precedence over all other options except `'clean'`.
Returns
stringSource
public static function insert($str, array $data, array $options = array()) {
$defaults = array(
'before' => '{:',
'after' => '}',
'escape' => null,
'format' => null,
'clean' => false
);
$options += $defaults;
$format = $options['format'];
reset($data);
if ($format == 'regex' || (!$format && $options['escape'])) {
$format = sprintf(
'/(?<!%s)%s%%s%s/',
preg_quote($options['escape'], '/'),
str_replace('%', '%%', preg_quote($options['before'], '/')),
str_replace('%', '%%', preg_quote($options['after'], '/'))
);
}
if (!$format && key($data) !== 0) {
$replace = array();
foreach ($data as $key => $value) {
$value = (is_array($value) || $value instanceof Closure) ? '' : $value;
try {
if (is_object($value) && method_exists($value, '__toString')) {
$value = (string) $value;
}
} catch (Exception $e) {
$value = '';
}
$replace["{$options['before']}{$key}{$options['after']}"] = $value;
}
$str = strtr($str, $replace);
return $options['clean'] ? static::clean($str, $options) : $str;
}
if (strpos($str, '?') !== false && isset($data[0])) {
$offset = 0;
while (($pos = strpos($str, '?', $offset)) !== false) {
$val = array_shift($data);
$offset = $pos + strlen($val);
$str = substr_replace($str, $val, $pos, 1);
}
return $options['clean'] ? static::clean($str, $options) : $str;
}
foreach ($data as $key => $value) {
$hashVal = crc32($key);
$key = sprintf($format, preg_quote($key, '/'));
if (!$key) {
continue;
}
$str = preg_replace($key, $hashVal, $str);
$str = str_replace($hashVal, $value, $str);
}
if (!isset($options['format']) && isset($options['before'])) {
$str = str_replace($options['escape'] . $options['before'], $options['before'], $str);
}
return $options['clean'] ? static::clean($str, $options) : $str;
}