0

我有一个包含以下链接的 HTML 页面

<a class="out" href="www.a.com/hgfgtsdfdffsdfsdf">sdfsssdfddf</a>
<a href="www.a.com/hgfgt">dsfdsf</a>
<a class="menu" href="www.a.com/hgfgt">menu1</a>
<a class="menu" href="www.a.com/hgfgdfg">menu2</a>
<a class="menu" href="www.a.com/hgfgdfg">menu3</a>
<a href="www.a.com/hgfgtssdfdfsdf">sdfsdfddf</a>
<a href="www.a.com/hgfgtsdfsfsdfdf">sdfsdfsddf</a>
<a href="www.a.com/hgfgtsdfsdfsdf">sdfsdfddf</a>
<a class="out" href="www.a.com/hgfgtsdfsdfsdf">sdfsdfddf</a>

我想使用 PHP 将类“菜单”的链接及其标题提取到一个数组中,请帮助我。

4

3 回答 3

0
preg_match_all('#<a class="menu" href="([^"]+)">([^<]+)</a>#', $content, $matches);
于 2012-04-05T10:34:09.913 回答
0
$str = '<a class="out" href="www.a.com/hgfgtsdfdffsdfsdf">sdfsssdfddf</a>
<a href="www.a.com/hgfgt">dsfdsf</a>
<a class="menu" href="www.a.com/hgfgt">menu1</a>
<a class="menu" href="www.a.com/hgfgdfg">menu2</a>
<a class="menu" href="www.a.com/hgfgdfg">menu3</a>
<a href="www.a.com/hgfgtssdfdfsdf">sdfsdfddf</a>
<a href="www.a.com/hgfgtsdfsfsdfdf">sdfsdfsddf</a>
<a href="www.a.com/hgfgtsdfsdfsdf">sdfsdfddf</a>
<a class="out" href="www.a.com/hgfgtsdfsdfsdf">sdfsdfddf</a>';

preg_match_all('#<a class="menu" href="([^"]+)">([^<]+)#', $str, $m);

var_dump($m[1], $m[2]);
于 2012-04-05T10:36:14.810 回答
0

以下是使用 DOMDocument 和 XPath 的方法:

$html = '

<a class="out" href="www.a.com/hgfgtsdfdffsdfsdf">sdfsssdfddf</a>
<a href="www.a.com/hgfgt">dsfdsf</a>
<a class="menu" href="www.a.com/hgfgt">menu1</a>
<a class="menu" href="www.a.com/hgfgdfg">menu2</a>
<a class="menu" href="www.a.com/hgfgdfg">menu3</a>
<a href="www.a.com/hgfgtssdfdfsdf">sdfsdfddf</a>
<a href="www.a.com/hgfgtsdfsfsdfdf">sdfsdfsddf</a>
<a href="www.a.com/hgfgtsdfsdfsdf">sdfsdfddf</a>
<a class="out" href="www.a.com/hgfgtsdfsdfsdf">sdfsdfddf</a>

';

$classname = 'menu'; // class to find

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXPath($doc);

$result = $xpath->query("//*[contains(@class, '$classname')]");

foreach($result as $elem)
{
    echo "title: " . $elem->nodeValue . "<br />";
    echo "link: " . $elem->getAttribute('href') . "<br />";
}
于 2012-04-05T10:50:10.297 回答