Support the ongoing development of Laravel.io →
posted 10 years ago
Input
Last updated 2 years ago.
0
$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.

Last updated 2 years ago.
0
$str = 'Hello :name. Do you like :drink?';
echo str_replace([':name', ':drink'], ['Ricardo', 'Coffee'], $str);
Last updated 2 years ago.
0

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?
Last updated 2 years ago.
0

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);    
}
Last updated 2 years ago.
0

@aheinzm Your answer is even more clean than the correct answer. Looks so nice.

Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.