简体   繁体   中英

(PHP) How to replace different substrings inside string using an array of values?

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!

Try below:

<?php
$subject = '%s is the best %s of the world.';
$values = array('FIAT', 'car');
echo vsprintf($subject, $values);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM