【问题标题】:Find link from page code with preg_match使用 preg_match 从页面代码中查找链接
【发布时间】:2014-09-01 14:59:59
【问题描述】:

我想用 preg_match 改变它:

<li class="fte_newsarchivelistleft" style="clear: both; padding-left:0px;"><a class="fte_standardlink fte_edit" href="news,2480143,3-kolejka-sezonu-2014-2015.html">3 kolejka sezonu 2014/2015&nbsp;&raquo;&raquo;</a></li>
                      <li class="fte_newsarchivelistright" style="height: 25px;">komentarzy: <span class="fte_standardlink">[0]</span></li>

到这里:

news,2480143,3-kolejka-sezonu-2014-2015.html

我该怎么做?我正在尝试使用 preg_match 但该链接太复杂了...

【问题讨论】:

    标签: php url hyperlink preg-match


    【解决方案1】:

    使用preg_match 确实太复杂了。正如该站点之前多次所述:正则表达式 + HTML 不能很好地混合。正则表达式不适合处理标记。然而,DOM 解析器是:

    $dom = new DOMDocument;//create parser
    $dom->loadHTML($htmlString);
    $xpath = new DOMXPath($dom);//create XPath instance for dom, so we can query using xpath
    $elemsWithHref = $xpath->query('//*[@href]');//get any node that has an href attribtue
    $hrefs = array();//all href values
    foreach ($elemsWithHref as $node)
    {
        $hrefs[] = $node->getAttributeNode('href')->value;//assign values
    }
    

    在此之后,处理$hrefs 中的值就很简单了,这将是一个字符串数组,每个字符串都是href 属性的值。

    另一个使用 DOM 解析器和 XPath 的示例(向您展示它可以做什么):can be found here

    要用href 值替换节点,很简单:

    • 获取父节点
    • 构建文本节点
    • 致电DOMDocument::replaceChild
    • 最后调用save 写入文件,或调用saveHTMLsaveXML 将DOM 作为字符串获取

    一个例子:

    $dom = new DOMDocument;//create parser
    $dom->loadHTML($htmlString);
    $xpath = new DOMXPath($dom);//create XPath instance for dom, so we can query using xpath
    $elemsWithHref = $xpath->query('//*[@href]');//get any node that has an href attribtue
    foreach ($elemsWithHref as $node)
    {
        $parent = $node->parentNode;
        $replace = new DOMText($node->getAttributeNode('href')->value);//create text node
        $parent->replaceChild($replace, $node);//replaces $node with $replace textNode
    }
    $newString = $dom->saveHTML();
    

    【讨论】:

    • @user3898993:如果您在处理标记时想到正则表达式,请记住:it summons Cthulhu... 这是一种传说中的答案 :)
    猜你喜欢
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多