按类名称的回声元素

时间:2014-02-20 21:26:30

标签: php html html-parsing

假设我在页面“tst.php”上有更多具有不同类名的href元素,如下所示:

<a class='1' href='etc.html'>Link</a>
<a class='2' href='etc.html'>Link</a>
<a class='3' href='etc.html'>Link</a>
<a class='4' href='etc.html'>Link</a>
<a class='5' href='etc.html'>Link</a>
<a class='1 2' href='etc.html'>Link</a>
<a class='1 4' href='etc.html'>Link</a>
<a class='5 2' href='etc.html'>Link</a>
<a class='2 3' href='etc.html'>Link</a>
<a class='2 1' href='etc.html'>Link</a>
<a class='5 2' href='etc.html'>Link</a>
<a class='5 2 6' href='etc.html'>Link</a>
<a class='5 2 6 7' href='etc.html'>Link</a>
<a class='5 2 5 7 8 9 4 6 2 6' href='etc.html'>Link</a>

我想制作一个PHP代码,它将在另一个页面“echo.php”中回显一个href的元素,这些元素在其值中有类名2。

像这样的东西

<?php
$stream = readfile("tst.php");
$regex = "class= '2'"
preg_match_all($regex,$Text,$Match);
echo $Match all;
?>

回声应该只是以“2”命名的类的Href:

<a class='2' href='etc.html'>Link</a>
<a class='1 2' href='etc.html'>Link</a>
<a class='5 2' href='etc.html'>Link</a>
<a class='2 3' href='etc.html'>Link</a>
<a class='5 2' href='etc.html'>Link</a>
<a class='5 2 6' href='etc.html'>Link</a>
<a class='5 2 6 7' href='etc.html'>Link</a>
<a class='5 2 5 7 8 9 4 6 2 6' href='etc.html'>Link</a>

提前致谢!

1 个答案:

答案 0 :(得分:3)

You shouldn't use regular expressions for parsing HTML。您应该使用为此设计的工具,如DomDocument。这是一个基本的例子:

<?php
$dom = new DOMDocument();
@$dom->loadHTML($string_with_html);
$anchors = $dom->getElementsByTagName('a');
foreach($anchors as $anchor) {
    $class = $anchor->getAttribute('class');
    if (strstr($class, '2')) {
        echo $dom->saveHTML($anchor) . "<br>\n";
    }
}

See it in action

您也可以使用xpath

$dom = new DOMDocument();
@$dom->loadHTML($string_with_html);
$xpath = new DOMXpath($dom);
$anchors = $xpath->query('//a[contains(@class,"2")]');
foreach ($anchors as $anchor) {
     echo $dom->saveHTML($anchor) . "<br>\n";
}