簡體   English   中英

(PHP)如何使用值數組替換字符串中的不同子字符串?

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

如何用子字符串數組替換字符串上的一組占位符?

我的代碼:

$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);

輸出:

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

所需輸出:

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

提前謝謝!

請嘗試以下方法:

<?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