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 に答える