0

How can I replace a set of placeholders on a string with an array of substrings?

My code:

$replaceWith = array('FIAT', 'car');
$message = '{%s} is the best {%s} of the world.';
$finalMessage = str_replace(array_fill(0, count($replaceWith), '{%s}'), $replaceWith, $message);

var_dump($finalMessage);

Outputs:

string 'FIAT is the best FIAT of the world.' (length=35)

Desired Output:

string 'FIAT is the best car of the world.' (length=34)

Thks in advance!

1 Answer 1

1

Try below:

<?php
$subject = '%s is the best %s of the world.';
$values = array('FIAT', 'car');
echo vsprintf($subject, $values);
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.