【发布时间】: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>
非常感谢任何建议。
谢谢!
【问题讨论】:
我想从以下这些标签中获取以“../category/”开头的网页的网址:
<a href="../category/product/pc.html" target="_blank">PC</a><br>
<a href="../category/product/carpet.html" target="_blank">Carpet</a><br>
非常感谢任何建议。
谢谢!
【问题讨论】:
不需要正则表达式。一个简单的带有 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
【讨论】:
$new_href = 'example.com/p/'.basename($node->getAttribute('href'));
此正则表达式搜索您的 ../category/ 字符串:
preg_match_all('#......="(\.\./category/.*?)"#', $test, $matches);
所有文本文字都用于匹配。您可以替换 ..... 以使其更具体。只有\. 需要转义。 .*? 查找可变长度字符串。而() 捕获匹配的路径名,因此它出现在 $matches 中。该手册解释了其余的语法。 http://www.php.net/manual/en/book.pcre.php
【讨论】: