【问题标题】:php regular expression to get the specific urlphp正则表达式获取具体的url
【发布时间】:2011-04-12 14:35:30
【问题描述】:

我想从以下这些标签中获取以“../category/”开头的网页的网址:

<a href="../category/product/pc.html" target="_blank">PC</a><br>
<a href="../category/product/carpet.html" target="_blank">Carpet</a><br>

非常感谢任何建议。

谢谢!

【问题讨论】:

    标签: php regex url


    【解决方案1】:

    不需要正则表达式。一个简单的带有 DOM 的 XPath 查询就足够了:

    $dom = new DOMDocument;
    $dom->loadHTML($html);
    $xpath = new DOMXPath($dom);
    
    $nodes = $xpath->query('//a[starts-with(@href, "../category/")]');
    foreach ($nodes as $node) {
        echo $node->nodeValue.' = '.$node->getAttribute('href').PHP_EOL;
    }
    

    将打印:

    PC = ../category/product/pc.html
    Carpet = ../category/product/carpet.html
    

    【讨论】:

    • 对不起,我以前没有用过这个,我想从链接中获取内容。类似“example.com/p/carpet.html”的东西。我将如何将其添加到代码中?
    • @user704278:如果你想重写 URL,只需:$new_href = 'example.com/p/'.basename($node-&gt;getAttribute('href'));
    【解决方案2】:

    此正则表达式搜索您的 ../category/ 字符串:

    preg_match_all('#......="(\.\./category/.*?)"#', $test, $matches);
    

    所有文本文字都用于匹配。您可以替换 ..... 以使其更具体。只有\. 需要转义。 .*? 查找可变长度字符串。而() 捕获匹配的路径名,因此它出现在 $matches 中。该手册解释了其余的语法。 http://www.php.net/manual/en/book.pcre.php

    【讨论】:

      猜你喜欢
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多