簡體   English   中英

php 正則表達式用於匹配錨標簽

[英]php regular expression for matching anchor tags

go 本頁來源:www.songs.pk/indian/7days.html

只有八個以http://link1開頭的鏈接

例如: <a href="http://link1.songs.pk/song1.php?songid=2792">Tune Mera Naam Liya</a>

我想要一個匹配的 php 正則表達式

http://link1.songs.pk/song1.php?songid=2792

Tune Mera Naam Liya

謝謝。

你最好使用simplehtmldom 之類的東西來查找所有鏈接,然后找到所有具有相關 HTML / href 的鏈接。

用正則表達式解析 HTML 並不總是最好的解決方案,在你的情況下,我覺得它只會給你帶來痛苦。

$href = 'some_href';
$inner_text = 'some text';

$desired_anchors = array();

$html = file_get_html ('your_file_or_url');

// Find all anchors, returns a array of element objects
foreach($html->find('a') as $anchor) {
    if ($a->href = $href && $anchor->innertext == $inner_text) {
        $desired_anchors[] = $anchor;
    }
}

print_r($desired_anchors);

那應該讓你開始。

不要使用正則表達式伙伴。 PHP 有一個更適合這個的工具......

$dom = new DOMDocument;

$dom->loadHTML($str);

$matchedAnchors = array();

$anchors = $dom->getElementsByTagName('a');

$match = 'http://link1';

foreach($anchors as $anchor) {

   if ($anchor->hasAttribute('href') AND substr($anchor->getAttribute('href'), 0, strlen($match)) == $match) {
      $matchedAnchors[] = $anchor;
   }

}

給你 go

preg_match_all('~<a .*href="(http://link1\..*)".*>(.*)</a>~Ui',$str,$match,PREG_SET_ORDER);
print_r($match);

暫無
暫無

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

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