首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用单词的多次出现完成一个句子

用单词的多次出现完成一个句子
EN

Stack Overflow用户
提问于 2014-01-15 06:44:46
回答 1查看 104关注 0票数 4

我有下面的句子

代码语言:javascript
复制
The boy is {good|better|best} in his {school|tution|class|scociety}

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

代码语言:javascript
复制
The boy is good in his school
The boy is good in his tution

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

代码语言:javascript
复制
good with this 4 {school|tution|class|scociety}

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

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

为此,我尝试如下:-

代码语言:javascript
复制
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 />';
}

但产出低于预期:-

代码语言:javascript
复制
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

有什么帮助吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-15 07:15:41

您最好在Regex中稍微修改一下,然后使用explode将它们放在数组中,然后使用循环来打印句子。

代码语言:javascript
复制
<?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";

输出

代码语言:javascript
复制
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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21130739

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档