2012-06-11 74 views
2

我已經研究過,需要找到最好的方法來隨機取代一系列可能性的需求。PHP的str_replace取代需要從數組中隨機替換?

即:

$text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time."; 

$keyword = "[city]"; 
$values = array("Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami"); 

$result = str_replace("[$keyword]", $values, $text); 

結果是每一次出現有 「陣列」 的城市。我需要用$ value中的隨機數來替換所有的城市事件。我想盡可能以最乾淨的方式做到這一點。我的解決方案迄今爲止是可怕的(遞歸)。什麼是最好的解決方案?謝謝!

回答

7

您可以使用preg_replace_callback執行功能的每場比賽,並返回替換字符串:

$text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time."; 

$keyword = "[city]"; 
$values = array("Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami"); 

$result = preg_replace_callback('/' . preg_quote($keyword) . '/', 
    function() use ($values){ return $values[array_rand($values)]; }, $text); 

樣品$result

歡迎來到亞特蘭大。我希望達拉斯每次都是隨機版本。邁阿密不應該每次都是亞特蘭大。

+0

天才答案。謝謝你爲我節省了很多時間。比我的遞歸混亂好多了:) –

0

您正在使用$values替換文本,它是一個數組,因此結果就是「數組」。替換應該是一個字符串。

您可以使用array_rand()從您的陣列中選取隨機條目。

$result = str_replace($keyword, $values[array_rand($values)], $text); 

的結果是這樣的:

Welcome to Atlanta. I want Atlanta to be a random version each time. Atlanta should not be the same Atlanta each time. 
Welcome to Orlando. I want Orlando to be a random version each time. Orlando should not be the same Orlando each time. 

如果你想在城市是隨機每行,檢查@ PaulP.R.O的答案。

+0

「[城市]應該是不一樣的[城市]每次」 – Hamish

+0

謝謝,rour解決方案相同的替換的偉大工程。但是,我需要在整個文檔中一次性進行可變更換。 :) –

0

試試這個http://codepad.org/qp7XYHe4

<? 
$text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time."; 

$keyword = "[city]"; 
$values = array("Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami"); 

echo $result = str_replace($keyword, shuffle($values)?current($values):$values[0], $text); 
+0

不起作用,因爲「[city]每次都不應該是同一個[city]」。這對每個替換使用相同的值。 – Hamish

5

你可以使用preg_replace_callbackarray_rand

<?php 
$text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time."; 

$values = array("Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami"); 

$result = preg_replace_callback("/\[city\]/", function($matches) use ($values) { return $values[array_rand($values)]; }, $text); 

echo $result; 

here

+0

這與PaulPRO的答案相同,並且完美。也謝謝你。 –

+0

是的,他打敗了我,所以我upvoted它:D – Hamish

1

這裏的另一個想法

$text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time."; 

$pattern = "/\[city\]/"; 
$values = array("Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami"); 

while(preg_match($pattern, $text)) { 
     $text = preg_replace($pattern, $values[array_rand($values)], $text, 1); 
} 

echo $text; 

和一些輸出:

Welcome to Orlando. I want Tampa to be a random version each time. Miami should not be the same Orlando each time.