簡體   English   中英

用數組PHP順序替換字符

[英]Replace characters sequentially with array PHP

我被命令本地化我們的網站。 嚴。

有問題的地方會作為我們的通知系統。 示例:您有3條新消息

希望本地字符串看起來像這樣:

You have % new messages

然后傳遞數字並將%替換為數字。

但是,如果我在某些地方想要多個數字,例如:

You have % new messages, and % alerts

我想在數組中傳遞兩個數字以替換第一個和第二個%

例:

$local->get(alert.message, array(3, 4))

alert.message對應於You have % new messages, and % alerts

最終輸出為: You have 3 new messages, and 4 alerts

您可以使用preg_replace設置替換次數的限制。 這樣,您可以執行以下操作:

$str = "You have % new messages, and % alerts";
$array = [3, 4];

foreach ($array as $a)
    $str = preg_replace("/%/", $a, $str, 1);

不給您代碼(同意Naruto的建議),但是sprintf應該可以提供幫助;-)

您也可以使用strtr

$str = "You have :messages new messages, and :alerts alerts";
echo strtr($str, [
    ':messages' => 5,
    ':alerts' => 10,
]);

或作為功能:

function strReplace($str, array $items) {
    return strtr($str, $items);
}

這有點多余(您可以直接調用strtr ,但確實會將其打包為一個函數。

使用命名參數也使代碼更易於閱讀。

值得注意的是,這對於安全性物品而言並不安全。 請注意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM