2011-07-31 40 views
0

任何人都可以帮我吗?假如我有this text或存储在一个变量中的小部分,我如何随机化'{}'中的单词?例如,第一个是“{important | essential | critical | critical | vital | significant}”我怎样才能让PHP随机选择一个单词然后回显它?感谢您的帮助。 :)使用PHP进行内容旋转?

+0

看看preg_replace_callback。 – erenon

+0

闻起来像是一个面试问题:) –

回答

3

http://webarto.com/62/random-sentence-spinning-function

function get_random($matches) 
{ 
    $rand = array_rand($split = explode("|", $matches[1])); 
    return $split[$rand]; 
} 

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

应用于您的文本文件... http://ideone.com/rkuf6

2
  • 剥离初始和结尾大括号,你可以使用trim()
  • 发生爆炸|生成的字符串使用explode()
  • 使用array_rand() f或您在最后一步中使用的阵列
+0

或使用preg_replace_callback :( – Kumar

+0

可能是这样的http://webarto.com/11/random-sentence-spinning,但它不会在递归括号上工作。 –

+0

看起来像bullet proof to我发现自己在正则表达式方面非常虚弱,并且喜欢使用较低价格的例程,所以很快提出了我的简单想法:-) – Kumar

1

不适用于嵌套({a | x {b | c} y | z})!

function doStuff($from){ 
    $to=""; 
    while(($pos=strpos($from,'{'))!==false){ 
     $to.=substr($from,0,$pos); 
     $from=substr($from,$pos); 
     $closepos=strpos($from,'}'); 
     $arr=explode('|',substr($from,1,$closepos-1)); 
     $to.=$arr[array_rand($arr)]; 
     $from=substr($from,$closepos+1); 
    } 
    return $to.$from; 
} 
+0

它不会在{{快速}快速}和{随机|意外} |旋转和随机}' –

+0

@webarto reliazed我的错误,编辑后 – RiaD