2017-01-30 46 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 –