php – 完成一个多次出现单词的句子
发布时间:2020-12-13 16:52:17 所属栏目:PHP教程 来源:网络整理
导读:我有下面的句子 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |