繁体   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