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

问题描述 投票:0回答:3

我正在尝试使用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 =“但我不能超越它。

php regex
3个回答
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能够以更少的痛苦来做到这一点......


0
投票

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

preg_match('#\b(width\s*=)\s*["\']?(\d+)#i', $source, $match);
print $match[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
© www.soinside.com 2019 - 2024. All rights reserved.