2008-11-05 53 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])];