【问题标题】:Select part of the URL inside an iframe tag选择 iframe 标记内的部分 URL
【发布时间】:2017-10-17 19:39:24
【问题描述】:
我需要捕获一个 ID,它是 iframe 标记内的 URL 的一部分。
我知道这可以用正则表达式完成,但我不是很擅长,我做了一些尝试但没有得到结果,iframe 会是这样(ID 可能会有所不同):
<iframe src="https://www.example.com/embed/ph57d6z9fa1349b" frameborder="0" height="481" width="608" scrolling="no"></iframe>
我想得到的 ID 是这样的:
ph57d6z9fa1349b
【问题讨论】:
标签:
php
regex
iframe
preg-match
【解决方案1】:
您可以使用正则表达式拆分字符串。
$re = '/\<iframe[^\>]+src\="(.+?)\/([A-Za-z0-9]+)"/';
$str = '<iframe src="https://www.example.com/embed/ph57d6z9fa1349b" frameborder="0" height="481" width="608" scrolling="no"></iframe>';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
如果您想列出 id 代码(例如“ph57d6z9fa1349b”),那么您可以这样做:
<?php
$re = '/\<iframe[^\>]+src\="(.+?)\/([A-Za-z0-9]+)"/';
$str = '<iframe src="https://www.example.com/embed/ph57d6z9fa1349b" frameborder="0" height="481" width="608" scrolling="no"></iframe>';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
foreach ($matches as $match) {
$id = $match[2]; // The required id code
echo $id; // Echo it
}
?>
【解决方案2】:
此正则表达式匹配源属性并将您的指定 ID 放入第 1 组。
src=".+\/(.+?)"
- 第一部分
src="匹配属性的开头
-
.+\/ 匹配 URL 正文直到最后一个斜杠(贪婪)
-
(.+?)" 匹配您的 id(惰性)和关闭属性的双引号