2017-01-30 57 views
0

在這裏與隨機字替換爲當前代碼: -對於striing字的每次出現,從陣列

function randommacrofunc($string){ 

    $RandomTextArray = array("Name","Think","Person","Apple","Orange","bananna"); 
    $count = substr_count($string, '{random}'); 
    $i = 0; 
    //re: 
    if ($i <= $count){ 
    shuffle($RandomTextArray); 
    $string = str_replace('{random}', $RandomTextArray[$i], $string, $i); 

    $i++; 
    //goto re; 
    } 

    return $string; 
} 

我的目標是由一個字代替在一個字符串的{random}每次出現從$RandomTextArray數組提取。當加載時,其替換正確的單詞,但所有相同的單詞。例:{random}{random}{random}AppleAppleApple位,我希望它返回ApplePersonThink

回答

2

嘗試使用此方法raplace機智隨機數組值:

<?php 
function randommacrofunc($string){ 

$RandomTextArray = array("Name","Think","Person","Apple","Orange","bananna"); 

$count = substr_count($string, '{random}'); // count number of `{randome}` in the string 

for ($i = 0;$i<$count;$i++){ // iterate for loop till the count reach 
     $string = preg_replace('/{random}/', $RandomTextArray[rand(0,(count($RandomTextArray)-1))], $string, 1); 
} 
return $string; // return final replaced string 
} 

$string = '{random} string {random} string {random} string {random} string {random} string {random}'; 
echo randommacrofunc($string); 
+0

是啊,這工作以及和更少的代碼比@Anant – btc4cash

+1

它會隨機更換工作。礦用於順序更換。 –

+1

@mith很好的努力BTW +1 –