用php改变字符串中的随机单词

时间:2014-01-21 13:57:21

标签: php

我正在寻找可以随机更改选择文本的内容spining功能。

前:

我有这样的文字:

$text = 'This is my nice text';

或本文:

$text = 'That is my beautiful text';

只有一个这样的规则:

$alternative '{(this|here|that)(nice|beautiful|cute)}';

有任何想法或方法吗?

3 个答案:

答案 0 :(得分:1)

我很快就像这样扔了一些东西:

    $string = "This is my nice text";

    $array = array("nice", "beautiful", "cute");

    $rand = $array[rand(0, 2)];

    echo str_replace("nice", $rand, $string);

我不知道这会有多好用。如果您想要其中一个,那么我想您可以通过foreach来运行它。

但是,如果您想要使用不同的选项,则必须执行多维数组。

$string = "This is my nice text";

$array = array(array("nice", "beautiful", "cute"), array("this", "here", "that"));

$choice_one = $array[1][rand(0,2)];
$choice_two = $array[0][rand(0,2)];

echo str_replace(array("This", "nice"), array($choice_one, $choice_two), $string);

这是在一个字符串中使用多个单词。

虽然效率不高......

答案 1 :(得分:1)

您可以使用explode将其拉入数组:

$textArray = explode(" ", $text);

规则有点不同,蛮力我认为你想要取出大括号,将其分解为“规则数组”(使用子字符串函数删除大括号,创建第一级规则数组基于括号,然后在管道上爆炸)所以你有一个看起来像这样的数组:

rule[0][0]->"this"
rule[0][1]->"here"
rule[0][2]->"that"
rule[1][0]->"nice"
rule[1][1]->"beautiful"
rule[1][2]->"cute"

根据您的输入,您可以这样做:

$alternative = substr_replace($alternative, "{(", 0);
$alternative = substr_replace($alternative, ")}", 0);
$rule=explode(")(",$alternative);
for ($i=0; $i<$rule.count(); i++){
    $rule[i]=explode("|",$rule[i]);
}

然后有一个三重嵌套的for循环,它根据规则数组的每个值进行文本阵列检查。在一个匹配上,你用来自规则数组的同一级别的随机值替换它,然后突破for循环的那个级别,这样它就不会再次验证。像这样:

foreach ($textArray as $i){
    for($x=0; $x<$rule.count(); $x++){
        for($y=0;$y<$rule[x].count(); $y++) {
            if ($i == $rule[$x][$y]) {
               $z=$y+1;
               if ($z == $rule[x].count()) {$z=0;}
               $i = $rule[$x][$z];
               break;
            }
        }
    }
}

答案 2 :(得分:-1)

相关问题