$values = ['name' => 'Ricardo', 'drink' => 'coffee'];
$str = "Hello " . $values['name'] . ".. Do you like " . $values['drink'] . "?";
echo $str;
Output: "Hello Ricardo.. Do you like coffee?"
Your helpers function can do likewise as what that $str assignment is doing - learn about string concatenation in PHP.
$str = 'Hello :name. Do you like :drink?';
echo str_replace([':name', ':drink'], ['Ricardo', 'Coffee'], $str);
Good.. But it has to be dynamic .. So.. My solution is..
function vnsprintf( $format, array $data)
{
preg_match_all( '/ (?<!%) % ( (?: [[:alpha:]_-][[:alnum:]_-]* | ([-+])? [0-9]+ (?(2) (?:\.[0-9]+)? | \.[0-9]+ ) ) ) \$ [-+]? \'? .? -? [0-9]* (\.[0-9]+)? \w/x', $format, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
$offset = 0;
$keys = array_keys($data);
foreach ( $match as &$value )
{
if ( ( $key = array_search( $value[1][0], $keys) ) !== FALSE || ( is_numeric( $value[1][0]) && ( $key = array_search( (int)$value[1][0], $keys) ) !== FALSE ) ) {
$len = strlen( $value[1][0]);
$format = substr_replace( $format, 1 + $key, $offset + $value[1][1], $len);
$offset -= $len - strlen( $key);
}
}
return vsprintf( $format, $data);
}
$str = "Hello %name\$s..Do you like %drink\$s?";
$values = array('name' => 'Ricardo', 'drink' => 'coffee');
echo vnsprintf( $str, $values);
// output: Hello Ricardo ..Do you like coffee?
This should allow your replaced text in your string and the replacing text in your arrays to be in any order.
$replace = [':drink' => 'coffee', ':name' => 'Ricardo'];
$str = 'Hi my name is :name. I like to drink :drink.';
echo str_replace_dynamic($replace, $str);
function str_replace_dynamic(array $replace, $string) {
return str_replace(array_keys($replace), array_values($replace), $string);
}
@aheinzm Your answer is even more clean than the correct answer. Looks so nice.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community