tags:

views:

80

answers:

1

Basically I want to use RegEx to grab stuff in between paragraphs in a document. I think the expression would be:

<p>.+?</p>

Say it grabs 10 items using this RegEx, I then want PHP to randomly choose one of those and then save it to a variable. Any ideas?

+7  A: 
// 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])];
Greg