2008-11-05 54 views
0

基本上我想用RegEx来抓取文档中的段落之间的东西。我想表达的是:随机RegEx在PHP中

<p>.+?</p> 

说它抓住使用这个正则表达式的10个项目,我再想PHP随机选择其中的一个,然后将其保存到一个变量。有任何想法吗?

回答

6
// Test data 
$str = '<p>a1</p><p>b2</p><p>c3</p><p>d4</p>'; 

// Pull out all the paragraph contents into $matches 
preg_match_all('_<p>(.+?)</p>_is', $str, $matches); 

// $matches[0] contains all the <p>....</p> 
// $matches[1] contains the first group, i.e. our (.+?) 
// Echo a random one 
echo $matches[1][array_rand($matches[1])];