2011-05-12 52 views
-1

可能重复:
Grabbing the href attribute of an A element提取URL使用PHP

嗨,我有这个字符串在PHP

<iframe frameborder="0" width="320" height="179" src="http://www.dailymotion.com/embed/video/xinpy5?width=320&wmode=transparent"></iframe><br /><a href="http://www.dailymotion.com/video/xinpy5_le-buzz-pippa-middleton-agace-la-reine_news" target="_blank">Le buzz Pippa Middleton agace la Reine !</a> <i>par <a href="http://www.dailymotion.com/direct8" target="_blank">direct8</a></i> 

我想从锚提取网址使用preg_match或其他php功能的href属性

回答

3

Don't use regexes to parse HTML。使用PHP DOM:

$DOM = new DOMDocument; 
$DOM->loadHTML($str); // Your string 

//get all anchors 
$anchors = $DOM->getElementsByTagName('a'); 

//display all hrefs 
for ($i = 0; $i < $anchors->length; $i++) 
    echo $anchors->item($i)->getAttribute('href') . "<br />"; 

您可以检查节点使用hasAttribute()必要时先有href

1

您可以使用

if (preg_match('#<a\s*[^>]*href="([^"]+)"#i', $string, $matches)) 
echo $matches[0]; 
0

尝试这个表达式

(?<=href=\")[\w://\.\-]+