如何匹配PHP正则表达式的特定文本链接

时间:2014-02-09 06:37:17

标签: php regex preg-match-all

这里我正在寻找PHP中的正则表达式,它将锚点与其上的特定“target =”_ parent“匹配。我希望获得带有以下文本的锚点:

preg_match_all('<a href="http://" target="_parent">Text here</a>', subject, matches, PREG_SET_ORDER);

HTML:

<a href="http://" target="_parent">

    <FONT style="font-size:10pt" color=#000000 face="Tahoma">
        <DIV><B>Text</B> - Text </DIV>
    </FONT>

</a>

</DIV>

2 个答案:

答案 0 :(得分:2)

您应该使用DOMDocument Class而不是Regex。如果使用Regex处理HTML,您将获得大量误报结果。

<?php

$html='<a href="http://" target="_parent">Text here</a>';
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $tag) {
    if ($tag->getAttribute('target') === '_parent') {
       echo $tag->nodeValue;
    }
}

<强> OUTPUT :

Text here

答案 1 :(得分:2)

说实话,最好的办法就是不要使用正则表达式。否则,您将错过各种不同的链接,特别是如果您不知道链接总是以相同的方式生成。

最好的方法是使用XML解析器。

<?php

$html = '<a href="http://" target="_parent">Text here</a>';
function extractTags($html) {
    $dom = new DOMDocument;
    libxml_use_internal_errors(true);
    $dom->loadHTML($html); // because dom will complain about badly formatted html
    $sxe = simplexml_import_dom($dom);
    $nodes = $sxe->xpath("//a[@target='_parent']");

    $anchors = array();
    foreach($nodes as $node) {
        $anchor = trim((string)dom_import_simplexml($node)->textContent);
        $attribs = $node->attributes();
        $anchors[$anchor] = (string)$attribs->href;
    }

    return $anchors;
}

print_r(extractTags($html))

这将输出:

Array (
    [Text here] => http://
)

即使在你的例子中使用它:

$html = '<a href="http://" target="_parent">

<FONT style="font-size:10pt" color=#000000 face="Tahoma">
        <DIV><B>Text</B> - Text </DIV>
            </FONT>

            </a>

            </DIV>
            ';
            print_r(extractTags($html));

将输出:

Array (
    [Text - Text] => http://
)

如果您觉得HTML仍然不够干净,无法与DOMDocument一起使用,那么我建议您使用HTMLPurifier等项目(请参阅http://htmlpurifier.org/)首先完全清理HTML(并删除不需要的HTML)并使用它的输出加载到DOMDocument。