我有一个名为$ featuresSEO的数组,其中包含许多单词,如:
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 :(得分:2)
逐个替换它们。这个将用随机单词替换每个出现。您可能会多次从$wordarray
看到相同的单词,因为它每次随机选择1个。
for ($i = 0; $i < substr_count($string, '|*-*|'); $i++){
$string = preg_replace('/\|\*-\*\|/',$wordarray[rand(0,count($wordarray)-1)],$string, 1);
}
想要只使用一次这个词吗?将数组洗牌并循环遍历:
shuffle($wordarray);
foreach ($wordarray as $word){
$string = preg_replace('/\|\*-\*\|/',$word,$string,1);
}
答案 1 :(得分: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;
第一个词出乎意料
答案 2 :(得分:0)
试试这个
<?php
$array = array("Japan","Japanese","Tokyo","Yokohama","Osaka","Asian","Nagoya");
$a = array_rand($array);
$string= "abc|*-*|";
echo str_replace("|*-*|", $array[$a], $string);
?>
答案 3 :(得分:0)
仅替换第一场比赛的代码来自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;