用于查找网址的正则表达式

时间:2013-07-22 03:29:41

标签: php regex html-parsing preg-match-all

<a href="http://newday.com/song.mp3">First Link</a>
<div id="right_song"> 
        <div style="font-size:15px;"><b>Pitbull ft. Chris Brown - Pitbull feat. Chris Brown - International Love mp3</b></div> 
        <div style="clear:both;"></div> 
<div style="float:left;"> 
    <div style="float:left; height:27px; font-size:13px; padding-top:2px;"> 
        <div style="float:left;"> 
    <a href="http://secondurl.com/thisoneshouldonlyoutput" rel="nofollow" target="_blank" style="color:green;">Second Link</a></div>'; 

我想使用pregmatch_all从这个html中获取第二个链接。我目前的正则表达式如下:

preg_match_all("/\<a.+?href=(\"|')(?!javascript:|#)(.+?)\.mp3(\"|')/i", $html, $urlMatches);

这工作正常,我得到两个链接输出,但我只想输出第二个没有.mp3扩展名。请帮帮我

1 个答案:

答案 0 :(得分:0)

描述

这个正则表达式

  • 匹配<div id="rigth_song">之后的第一个锚标记,其中href属性的值以.mp3结尾
  • 将避免许多边缘情况,这使得使用正则表达式匹配html文本非常困难。

<div\sid="right_song">.*?<a(?=\s|>)(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\shref=(['"]?)(.*?\.mp3)\1(?:\s|\/>|>))(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*>.*?<\/a>

enter image description here

实施例

示例文字

注意第二个锚标记中的困难边缘情况,如字符串href="bad.mp3"嵌套在属性值中;有一个javascript大于值>的值;而真正的href属性没有引号。

<a href="http://newday.com/song.mp3">First Link</a>
<div id="right_song"> 
        <div style="font-size:15px;"><b>Pitbull ft. Chris Brown - Pitbull feat. Chris Brown - International Love mp3</b></div> 
        <div style="clear:both;"></div> 
<div style="float:left;"> 
    <div style="float:left; height:27px; font-size:13px; padding-top:2px;"> 
        <div style="float:left;"> 
<a onmouseover=' href="bad.mp3" ; if ( 6 > x ) {funRotate(href); } ; ' href="http://secondurl.com/thisoneshouldonlyoutput.mp3">First Link</a>
</div>

<强>代码

<?php
$sourcestring="your source string";
preg_match('/<div\sid="right_song">.*?<a(?=\s|>)(?=(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*?\shref=([\'"]?)(.*?\.mp3)\1(?:\s|\/>|>))(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*>.*?<\/a>
/imsx',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>

<强>匹配

组0从<div获取文本到包括完全匹配的锚标记
的文本 第1组获得围绕href值的开头报价,后面将再次引用 第2组获得href值

[0] => <div id="right_song"> 
        <div style="font-size:15px;"><b>Pitbull ft. Chris Brown - Pitbull feat. Chris Brown - International Love mp3</b></div> 
        <div style="clear:both;"></div> 
<div style="float:left;"> 
    <div style="float:left; height:27px; font-size:13px; padding-top:2px;"> 
        <div style="float:left;"> 
<a onmouseover=' href="bad.mp3" ; if ( 6 > x ) {funRotate(href); } ; ' href="http://secondurl.com/thisoneshouldonlyoutput.mp3">First Link</a>
[1] => "
[2] => http://secondurl.com/thisoneshouldonlyoutput.mp3