显示preg match的所有匹配项

时间:2015-10-17 21:10:00

标签: php regex

如何显示所有结果而不仅仅是preg match中的第一个匹配?

这是$ show的内容:

<a href="http://website.com/one">One</a>
<a href="http://website.com/two">Two</a>
<a href="http://website.com/three">Three</a>

这是PHP代码:

preg_match("/<a href=\"(.+?)\">(.+?)<\/a>/", $show, $display);
$xml = "<name>".$display[2]."</name><link>".$display[1]."</link>";
echo $xml;

输出结果为:

<name>One</name><link>http://website.com/one</link>

但我想让它显示所有结果:

<name>One</name><link>http://website.com/one</link>
<name>Two</name><link>http://website.com/two</link>
<name>Three</name><link>http://website.com/three</link>

这是print_r的输出($ display); ...

Array
(
    [0] => Array
        (
            [0] => <a href="http://website.com/one">One</a>
            [1] => <a href="http://website.com/two">Two</a>
            [2] => <a href="http://website.com/three">Three</a>
        )

    [1] => Array
        (
            [0] => http://website.com/one
            [1] => http://website.com/two
            [2] => http://website.com/three
        )

    [2] => Array
        (
            [0] => One
            [1] => Two
            [2] => Three
        )

)

2 个答案:

答案 0 :(得分:4)

You would use preg_match_all()的默认操作获取所有匹配项,然后遍历它们:

preg_match_all('~<a href="(.+?)">(.+?)</a>~s', $html, $matches, PREG_SET_ORDER);

foreach ($matches as $m) {
  echo "<name>".$m[2]."</name><link>".$m[1]."</link>\n";
}

但我建议使用 DOM 代替此任务。

$doc = new DOMDocument;
$doc->loadHTML($html); // load the HTML data

foreach ($doc->getElementsByTagName('a') as $link) {
  echo "<name>".$link->nodeValue."</name><link>".$link->getAttribute('href')."</link>\n";
}

eval.in

答案 1 :(得分:1)

你可以这样吗

$xml = '';
$show = '<a href="http://website.com/one">One</a>
         <a href="http://website.com/two">Two</a>
         <a href="http://website.com/three">Three</a>';

preg_match_all("/<a href=\"(.+?)\">(.+?)<\/a>/", $show, $display);
for($i=0; $i<count($display[0]); $i++){
    $xml .= "<name>".$display[2][$i]."</name><link>".$display[1][$i]."</link>";
}
echo $xml;

,这将输出

<name>One</name><link>http://website.com/one</link><name>Two</name><link>http://website.com/two</link><name>Three</name><link>http://website.com/three</link>

<强> DEMO