加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – 完成一个多次出现单词的句子

发布时间:2021-08-28 03:46:18 所属栏目:大数据 来源: https://www.jb51.cc
导读:我有下面的句子 The boy is {good|better|best} in his {school|tution|class|scociety} 现在我需要创建一个递归的PHP函数,它将这个句子作为输入,并将输出如下: – The boy is good in his schoolThe boy is good in his tution 以类似的方式我需要创建12行

我有下面的句子

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

有什么帮助吗?

解决方法:

你最好在你的正则表达式中改变一点,然后使用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

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读