【问题标题】:complete a sentence with multiple occurance of words完成一个单词多次出现的句子
【发布时间】:2014-02-03 12:39:37
【问题描述】:

下面这句话

The boy is {good|better|best} in his {school|tution|class|scociety}

现在我需要创建一个递归 PHP 函数,它将这句话作为输入并输出如下:-

The boy is good in his school
The boy is good in his tution

以类似的方式,我需要创建 12 行,因为上面的句子有 12 个单词。如下:-

good with this 4 {school|tution|class|scociety}

better with this 4 {school|tution|class|scociety}

best with this 4 {school|tution|class|scociety}

为此,我尝试了以下方法:-

function get_random($matches)
{
    $part     = substr($matches[0], 1, strlen($matches[0])-2);
    $part     = show_randomized($part);
    $rand     = array_rand($split = explode("|", $part));
    return $split[$rand];
}

function show_randomized($str)
{
    $str = preg_replace_callback('/(\{[^}]*)([^{]*\})/im', "get_random", $str);
    return $str;
}

// Test

$rand_sentence = "The boy is {good|better|best} in his {school|tution|class|scociety}";

for ($i = 0; $i < 10; $i++)
{
    echo show_randomized($rand_sentence).'<br />';
}

但低于输出:-

The boy is best in his tution
The boy is better in his school
The boy is good in his tution
The boy is better in his school
The boy is better in his scociety
The boy is best in his tution
The boy is better in his class
The boy is good in his school
The boy is best in his tution
The boy is best in his school

有什么帮助吗?

【问题讨论】:

    标签: php regex arrays random-sample


    【解决方案1】:

    你最好在你的正则表达式中稍作改动,然后使用explode 将它们放入一个数组中,然后使用循环打印出句子。

    <?php
        $str = "The boy is {good|better|best} in his {school|tution|class|scociety}";
        preg_match_all("/\{([^}]+)\}/", $str, $match);
        $arr = array_map(function($value){
            return explode("|", $value);
        }, $match[1]);
        foreach($arr[0] as $adj)
            foreach($arr[1] as $name)
                echo "The boy is {$adj} in his {$name}\n";
    

    输出

    The boy is good in his school
    The boy is good in his tution
    The boy is good in his class
    The boy is good in his scociety
    The boy is better in his school
    The boy is better in his tution
    The boy is better in his class
    The boy is better in his scociety
    The boy is best in his school
    The boy is best in his tution
    The boy is best in his class
    The boy is best in his scociety
    

    【讨论】:

    • 您的正则表达式模式给出以下输出:- Array ( [0] => Array ( [0] => {good|better|best} [1] => {school|tution|class| scociety} ) [1] => 数组 ( [0] => 好|更好|最好 [1] => school|tution|class|scociety ) )
    • 你应该使用lookarounds/(?&lt;={)[^}]*(?=})/
    • @SamSullivan 我为什么要使用它?
    • 您将得到一个简单的数组而不是多维数组,我认为这会使代码更具可读性(并可能节省可忽略不计的内存量)。但我想没什么大不了的。
    • @SamSullivan 在这种情况下并不重要。
    猜你喜欢
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2022-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多