【发布时间】:2014-01-16 07:08:35
【问题描述】:
下面的句子,
{Please|Just} make this {cool|awesome|random} test sentence {rotate {quickly|fast} and random|spin and be random}
我需要创建一个 random() 函数,它将给出以下输出:-
Please make this cool test sentence rotate fast and random.
OR
Just make this random test sentence spin and be random.
我不知道该怎么做。
我在下面尝试过,但没有得到结果。
echo spinningFunction($str);
function spinningFunction($str)
{
$output = "";
$pattern = "/\[.*?\]|\{.*?\}/";
preg_match_all($pattern, $str, $match);
$arr = array_map(function($value){
return explode("|", $value);
}, $match[1]);
foreach($arr[0] as $adj)
foreach($arr[1] as $name)
$output.= "{$adj} make this {$name} test sentence<br />";
return $output;
}
有什么帮助吗?
编辑:-
function spinningFunction($str)
{
$str = preg_replace_callback('/(\{[^}]*)([^{]*\})/im', "spinningFunction", $str);
return $str;
}
有人能帮我从上面的句子中实现如下所示的数组吗:-
Array
(
[0] => Array
(
[0] => {Please|Just}
[1] => {cool|awesome|random}
[2] => {rotate {quickly|fast} and random|spin and be random}
)
)
【问题讨论】:
-
您的正则表达式中没有任何捕获组,因此
$match[1]不包含任何内容。你想要$match[0]。 -
你的随机码在哪里?你只是输出每个组合。请参阅 stackoverflow.com/questions/4233407/get-random-item-from-array 了解如何选择数组的随机元素。
-
是的。但 $match[0] 也没有给我数组中的确切 3 元素:(
-
@Barmar 尚未应用。实际上,到目前为止,我还无法迈出第一步。 :(
-
@Barmar 请查看我编辑的代码。我试图使用类似的代码
标签: php regex function random-sample