简体   繁体   English

(PHP)如何使用值数组替换字符串中的不同子字符串?

[英](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);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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