1

Say I do this:

$string = 'some string with a {$var}';

// Set var after
$var = 'variable'

// String with just set var
$newString = 'Here is my string: ' . $string;
echo $newString;

How would I make it output:

Here is my string: some string with a variable

I could do it with str_replace(), but I was wondering if there was an easier way?

0

1 Answer 1

7

Based on your example I think sprintf() would work for you:

$string = 'some string with a %s';
$var = 'variable';
$newString = sprintf($string, $var);
Sign up to request clarification or add additional context in comments.

1 Comment

+1, one can also use printf() in this case. printf() will directly output the string instead of returning it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.