lithium\util\Text::insert()
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:
Text::insert(
'My name is {:name} and I am {:age} years old.',
['name' => 'Bob', 'age' => '65']
); // returns 'My name is Bob and I am 65 years old.'
Please note that optimization have applied to this method and parts of the code may look like it can refactored or removed but in fact this is part of the applied optimization. Please check the history for this section of code before refactoring
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 forText::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 = []) {
$defaults = [
'before' => '{:',
'after' => '}',
'escape' => null,
'format' => null,
'clean' => false
];
$options += $defaults;
$format = $options['format'];
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 = [];
foreach ($data as $key => $value) {
if (!is_scalar($value)) {
if (is_object($value) && method_exists($value, '__toString')) {
$value = (string) $value;
} else {
$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) {
if (!$key = sprintf($format, preg_quote($key, '/'))) {
continue;
}
$hash = crc32($key);
$str = preg_replace($key, $hash, $str);
$str = str_replace($hash, $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;
}