php pcre额外的括号

时间:2012-02-12 06:34:42

标签: php regex

 $regex = '/<A HREF="(.*)">(1080p)</A><BR>/i';
 preg_match_all($regex, $homepage, $matches);

如何阻止preg_match尝试查找1080p并找到(。*)。

<b>(Yahoo)</b><br>
<b>(High Definition)</b><br>
<a href="http://playlist.yahoo.com/makeplaylist.dll?sid=107193280&amp;sdm=web&amp;pt=rd">(1080p)</a><br>
<a href="http://playlist.yahoo.com/makeplaylist.dll?sid=107193279&amp;sdm=web&amp;pt=rd">(720p)</a><br>
<a href="http://playlist.yahoo.com/makeplaylist.dll?sid=107193272&amp;sdm=web&amp;pt=rd">(480p)</a><br>
<br>
<b>(Warner Bros.)</b><br>
<b>(High Definition)</b><br>
<a href="http://pdl.warnerbros.com/wbmovies/inception/trl_3/Inception_TRLR3_1080.mov">(1080p)</a><br>
<a href="http://pdl.warnerbros.com/wbmovies/inception/trl_3/Inception_TRLR3_720.mov">(720p)</a><br>
<a href="http://pdl.warnerbros.com/wbmovies/inception/trl_3/Inception_TRLR3_480.mov">(480p)</a><br>
</p>
</div>
<br>

1 个答案:

答案 0 :(得分:1)

将1080p放入非捕获组:

$regex = '#<A HREF="(.*)">(?:1080p)</A><BR>#i';

或者更好的是,消除群体:

$regex = '#<A HREF="(.*)">1080p</A><BR>#i';

如果你有“(1080p)”作为字符串,请转义括号:

$regex = '#<A HREF="(.*)">\(1080p\)</A><BR>#i';

这是适用于您的应用程序的更好的正则表达式;

$regex = '#<a href="([^"]+)">\(\d{3,4}p\)</a><br>#i';
$html  = '<a href="http://pdl.warnerbros.com/wbmovies/inception/trl_3/Inception_TRLR3_1080.mov">(1080p)</a><br>
<a href="http://pdl.warnerbros.com/wbmovies/inception/trl_3/Inception_TRLR3_720.mov">(720p)</a><br>
<a href="http://pdl.warnerbros.com/wbmovies/inception/trl_3/Inception_TRLR3_480.mov">(480p)</a><br>';
preg_match_all( $regex, $html, $matches);

var_dump( $matches[1]);

输出:Demo

array(3) {
  [0]=>
  string(75) "http://pdl.warnerbros.com/wbmovies/inception/trl_3/Inception_TRLR3_1080.mov"
  [1]=>
  string(74) "http://pdl.warnerbros.com/wbmovies/inception/trl_3/Inception_TRLR3_720.mov"
  [2]=>
  string(74) "http://pdl.warnerbros.com/wbmovies/inception/trl_3/Inception_TRLR3_480.mov"
}