我试图从Feed中提取特定链接,其中所有内容都在一行上,并且存在多个链接。我想要的是" [link]"在A标签中。这是我的榜样:
<a href="google.com/">test1</a> <a href="google.com/">test2</a> <a href="http://www.amazingpage.com/">[link]</a> <a href="google.com/">test3</a><a href="google.com/">test4</a>
... could be more links before and/or after
如何仅将href与内容隔离&#34; [link]&#34;?
这个正则表达式转到我想要的块的正确结尾,但是从第一个链接开始:
(?<=href\=\").*?(?=\[link\])
任何帮助将不胜感激!感谢。
答案 0 :(得分:3)
试试这个更新的正则表达式:
(?<=href\=\")[^<]*?(?=\">\[link\])
见demo。
问题是,点匹配太多字符,以便获得正确的&#39; href&#39;你需要将正则表达式限制为[^<]*?
。
答案 1 :(得分:2)
或者:)
此代码:
$string = '<a href="google.com/">test1</a> <a href="google.com/">test2</a> <a href="http://www.amazingpage.com/">[link]</a> <a href="google.com/">test3</a><a href="google.com/">test4</a>';
$regex = '/href="([^"]*)">\[link\]/i';
$result = preg_match($regex, $string, $matches);
var_dump($matches);
将返回:
array(2) {
[0] =>
string(41) "href="http://www.amazingpage.com/">[link]"
[1] =>
string(27) "http://www.amazingpage.com/"
}
答案 2 :(得分:1)
您可以避免使用正则表达式并使用DOM来执行此操作。
$doc = DOMDocument::loadHTML('
<a href="google.com/">test1</a>
<a href="google.com/">test2</a>
<a href="http://www.amazingpage.com/">[link]</a>
<a href="google.com/">test3</a>
<a href="google.com/">test4</a>
');
foreach ($doc->getElementsByTagName('a') as $link) {
if ($link->nodeValue == '[link]') {
echo $link->getAttribute('href');
}
}
答案 3 :(得分:1)
使用DOMDocument和XPath:
$dom = DOMDOcument::loadHTML($yourHTML);
$xpath = DOMXPath($dom);
foreach ($xpath->query('//a[. = "[link]"]/@href') as $node) {
echo $node->nodeValue;
}
或者如果您只想找到一个结果:
$dom = DOMDOcument::loadHTML($yourHTML);
$xpath = DOMXPath($dom);
$nodeList = $xp->query('//a[. = "[link]"][1]/@href');
if ($nodeList->length)
echo $nodeList->item(0)->nodeValue;
xpath查询详情:
//a # 'a' tag everywhere in the DOM tree
[. = "[link]"] # (condition) which has "[link]" as value
/@href # "href" attribute
你的正则表达式模式不起作用的原因:
正则表达式引擎从左向右行走,并且对于字符串中的每个位置,它都会尝试成功。因此,即使您使用非贪婪量词,您也始终获得最左边的结果。