任何人都可以用正则表达式帮助我吗?

时间:2011-03-31 20:44:30

标签: php regex

我正在尝试使用preg_match从嵌入代码中提取YouTube视频的宽度。

代码如下:

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/3uw-nUvGrBY" frameborder="0" allowfullscreen></iframe>

我想提取width =“480”

我试过了:

/width="[0-9]+"/
/width=\"[0-9]+\"/
/width=.[0-9]+./

但它们都不起作用。如果我删除最后的双引号和数字,我可以提取width =“但我不能超越它。

3 个答案:

答案 0 :(得分:0)

$string = '<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/3uw-nUvGrBY" frameborder="0" allowfullscreen></iframe>';
preg_match('/.*width="(\d+)".*/', $string, $match);\
echo $match[1];

但我确信,PHP或JS DOM能够轻松实现这一目标......

答案 1 :(得分:0)

您的实际来源可能格式不同。您的示例html代码段看起来非常典范。试试这个:

preg_match('#\b(width\s*=)\s*["\']?(\d+)#i', $source, $match);
print $match[2];

答案 2 :(得分:0)

$ptn = "/(?<=width=\")\d*(?=\")/";
$str = '<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/3uw-nUvGrBY" frameborder="0" allowfullscreen></iframe>';
preg_match($ptn, $str, $matches);
echo $matches[0]; // 480
相关问题