簡體   English   中英

PHP正則表達式以獲取特定的URL

[英]php regular expression to get the specific url

我想從以下這些標記中以“ ../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

此正則表達式搜索您的../category/字符串:

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

所有文本文字均用於匹配。 您可以替換...以使其更具體。 只有\\. 需要逃脫。 .*? 尋找一個可變長度的字符串。 ()捕獲匹配的路徑名,因此它出現在$ matches中。 該手冊介紹了其余語法。 http://www.php.net/manual/en/book.pcre.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM