我有一個腳本可以生成包含某些標記的內容,我需要用一個單獨的循環來替換每個出現的標記。使用不同的值替換多次出現的字符串
它使用簡單,str_replace函數與相同內容替換令牌的所有事件,但我需要與循環的下一個結果替換每次出現。
我沒有看到這樣的回答:Search and replace multiple values with multiple/different values in PHP5?
但它是從預先定義的數組,我沒有工作。
示例內容:
This is an example of %%token%% that might contain multiple instances of a particular
%%token%%, that need to each be replaced with a different piece of %%token%% generated
elsewhere.
我需要更換的每次出現%%令牌%%的內容產生的,爲了便於討論,通過這種簡單的循環:
for($i=0;$i<3;$i++){
$token = rand(100,10000);
}
所以替換每個% %token %%與一個不同的隨機數值$ token。
這是一些簡單的,我只是沒有看到?
謝謝!
我不認爲有一個庫函數爲你做這個。您只需編碼搜索並替換自己。 –
我知道這一點,我正在尋求幫助。我一直無法圍繞解決方案來解決這個問題。我的preg_replace技能不是很好,但我發現了一些看起來很有用的東西,但我無法弄清楚如何修改它以滿足我的需求: $ string ='某個foo的時間,因爲它是我們想要的foo和我們會得到。因爲它是我們想要的,我們會得到的foo。 $ replaceme ='foo'; $ replacewith ='bar'; $ nthtimes = 2; echo preg_replace(「/ ((.*?))(".$ replaceme。」)){「。$ nthtimes。」}/e「,'(preg_replace(」/".$ replaceme。「$ /」, 「」,「\ 0」))。$ replacewith',$ string); –
對不起,誤解了這個問題。見答案。 –