2012-02-27 31 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; 

第一个字变成意想不到的