2012-02-27 78 views
1

我已經是擁有一批在它的話叫$ featuresSEO數組喜歡:PHP隨機更換的話

Array (
    [0] => Japan 
    [1] => Japanese 
    [2] => Tokyo 
    [3] => Yokohama 
    [4] => Osaka 
    [5] => Asian 
    [6] => Nagoya 
) 

然後我有一個字符串像如下:

Searching the |*-*| Dating membership database is the key to locating |*-*| people 
you would be interested in. You can search for |*-*| Singles including |*-*| Women 
and |*-*| Men in any location worldwide. Join now to search for |*-*| Singles. 

我一直試圖用來自陣列的隨機單詞替換|*-*|的實例。我試過str_replace(),但無法獲得隨機方面的工作。

有人能把我推向正確的方向嗎?

thx

+0

是每個'| * - * |'隨機,還是一個隨機單詞,然後用於所有'| * - * |'? – 2012-02-27 08:30:44

+0

每一個隨機單詞...通過字符串如此不同的單詞 – Adam 2012-02-27 08:31:37

+0

使用random()函數獲得一個隨機索引,然後用你的'Array [your_random_index]' – 2012-02-27 08:31:49

回答

0

的代碼替換,僅一-match是從here借來的。以下代碼只使用列表中的每個單詞一次:

$wordlist = array(
    'Japan', 
    'Japanese', 
    'Tokyo', 
    'Yokohama', 
    'Osaka', 
    'Asian', 
    'Nagoya' 
); 
$string = " 
Searching the |*-*| Dating membership database is the key to locating |*-*| people 
you would be interested in. You can search for |*-*| Singles including |*-*| Women 
and |*-*| Men in any location worldwide. Join now to search for |*-*| Singles. 
"; 
$replace = '|*-*|'; 
while(true){ 
    $index = strpos($string, $replace); 
    if($index === false){ 
     // ran out of place holder strings 
     break; 
    } 
    if(count($wordlist) == 0){ 
     // ran out of words 
     break; 
    } 
    $word = array_splice($wordlist, rand(0, count($wordlist) - 1), 1); 
    $string = substr_replace($string, $word[0], $index, strlen($replace)); 
} 
echo $string; 
2

將它們逐一替換。這一個將用隨機詞代替每個事件。您可能會多次看到$wordarray中的相同單詞,因爲它每次隨機選取1個單詞。

for ($i = 0; $i < substr_count($string, '|*-*|'); $i++){ 
    $string = preg_replace('/\|\*-\*\|/',$wordarray[rand(0,count($wordarray)-1)],$string, 1); 
} 

想要只使用每個單詞一次嗎?通過它shuffle的陣列,並循環:

shuffle($wordarray); 
foreach ($wordarray as $word){ 
    $string = preg_replace('/\|\*-\*\|/',$word,$string,1); 
} 
+0

將使用第一個隨機選擇的項目替換所有項目,是不是? – 2012-02-27 08:35:32

+0

nope。我已經把'1'作爲第四個參數。所以它只會取代1次出現 – 2012-02-27 08:36:15

+0

第四個參數給我一個警告! – 2012-02-27 08:43:16

0

試試這個

<?php 
    $array = array("Japan","Japanese","Tokyo","Yokohama","Osaka","Asian","Nagoya"); 
    $a = array_rand($array); 
    $string= "abc|*-*|"; 
    echo str_replace("|*-*|", $array[$a], $string); 
?> 
2

試試這個

$string = ' Searching the |*-*| Dating membership database is the key to locating |*-*| people 
you would be interested in. You can search for |*-*| Singles including |*-*| Women 
and |*-*| Men in any location worldwide. Join now to search for |*-*| Singles.'; 

$words = array('Japanese', 'Tokyo', 'Asian'); 

$placeholder = '|*-*|'; 
$pos = null; 

while(null === $pos || false !== $pos) { 
    $pos = strpos($string, $placeholder); 
    $string = substr_replace($string, $words[rand(0, count($words)-1)], $pos, strlen($placeholder)); 

} 

echo $string; 

第一個字變成意想不到的