Today is a sunny day
我想接受is
并用三个随机词替换它。
所以:Today {was|wasn't|isn't} a sunny day
但是,如果is
在另一个有五次出现的字符串中(比如一篇文章),我想用{was|wasn't|isn't}
我怎样才能做到这一点?
到目前为止,我知道你必须使用str_replace,在foreach循环中有一个数组。但是我无法让它发挥作用。
非常感谢任何帮助。
谢谢!
答案 0 :(得分:0)
试试这个:
$replacements = array("was", "wasn't", "isn't");
preg_replace("/\wis\w/e", "$replacements[array_rand($replacements)]", $text);
搜索到的正则表达式中的“e”修饰符会导致替换字符串被评估为PHP代码。然后使用array_rand从$ replacementments
中选择一个随机密钥答案 1 :(得分:0)
替代方式......
$str = "Today is a sunny day";
$findme = "is";
$arr = array("was","wasn't","isn't");
$tmp = explode("is",$str);
$str = $tmp[0];
for($i=1;$i<count($tmp);$i++)
$str .= array_rand($arr) . $tmp[$i];
答案 2 :(得分:0)
请在此处查看此解决方案
$d = array("was","wasn't","isn't");
$st = "Today is a sunny day, is it not?";
$arr = explode(" ", $st);
for($i=0;$i<count($arr);$i++){
if ($arr[$i] == "is"){
$r = rand(0, 2);
$arr[$i] = $d[$r];
}
}
foreach($arr as $v){
echo $v." ";
}
?>
输出
Today wasn't a sunny day, was it not?