在PHP中随机化RegEx
问题描述:
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?
基本上我想使用RegEx来抓取文档中段落之间的内容。 我认为表达式为: p>
&lt; p&gt;。+?&lt; / p&gt;
code> pre>
假设它使用此RegEx抓取10个项目,然后我希望PHP随机选择其中一个,然后将其保存到变量。 有什么想法吗? p>
div>
答
// 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])];