php - 如果预匹配,则从双引号中提取媒体
问题描述
我正在获取一个站点的 file_get_content,它返回给我这个
<meta property="og:video:secure_url" content="//abc-def-
ghi.net/reg02/2016/05/31/05/92f24c57-2cb3-42b0-84cb-edad24d7b68f.mp4?
secure=1"><meta property="og:video:type" content="video/mp4"><meta
property="og:video:width" content="540"><meta property="og:video:height"
content="960"><meta property="fb:app_id" content="682659535154406">
如您所见, 内容被多次写入。我想要做的是,如果我搜索.mp4并且如果在某些内容中找到,那么它将复制该双引号内的整个数据例如在上面的代码中,它将提取并给我
//mpak-suse1.akamaized.net/reg02/2016/05/31/05/92f24c57-2cb3-42b0-84cb-edad24d7b68f.mp4?secure=1
我对如何做到这一点感到很困惑,所以没有编写任何代码。我发现另一种解决方案是在函数之间使用 get string
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$link = get_string_between($output, '<meta property="og:video:secure_url" content="', '">');
但它看起来不太可靠。我要求的东西可以帮助不同项目中的许多其他人。如果有人可以请启发这个话题
解决方案
大多数 StackOverflow 志愿者建议使用像 DomDocument 或类似的 dom 解析器来有效/可靠地解析 html 数据。
代码:(演示)
$html = <<<HTML
<meta property="og:video:secure_url" content="//abc-def-
ghi.net/reg02/2016/05/31/05/92f24c57-2cb3-42b0-84cb-edad24d7b68f.mp4?
secure=1"><meta property="og:video:type" content="video/mp4"><meta
property="og:video:width" content="540"><meta property="og:video:height"
content="960"><meta property="fb:app_id" content="682659535154406"><meta property="test" nocontent="bad">
HTML;
$dom=new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName("meta") as $meta) {
if ($meta->hasAttribute('content') && strpos($content = $meta->getAttribute('content'), '.mp4')) {
$result[] = $content;
}
}
var_export($result);
输出:
array (
0 => '//abc-def-
ghi.net/reg02/2016/05/31/05/92f24c57-2cb3-42b0-84cb-edad24d7b68f.mp4?
secure=1',
)
*作为记录,是的,我知道测试false
withstrpos()
因为 offset0
和false
松散地评估为false
,但从逻辑上讲,如果该content
值以它开头,.mp4
它将不是一个可用/合格的值。
推荐阅读
- java - layoutInflater.inflate() 方法无法解析 layoutName
- javascript - 如何在 JavaScript 中获取渐变颜色的十六进制代码(基于值的 3 种颜色)
- python - 从一个文件运行多个 Python 脚本
- mysql - MySQL按日期排序其中日期> =今天在升序中,然后日期<今天在1个查询中降序
- libgdx - 如何强制 OpenAL 与 libgdx 中的 pulseaudio 交互?(适用于 GNOME,但不适用于 i3)
- python-3.x - 从先前训练的模型 Tensorflow 预测
- codenameone - GUI Builder 中的 Cant design 对话框
- c# - Wordpress 5.2.2 和 selenium:无法找到正文帖子(不在 iframe 或 TinyMCE 中的富文本编辑器)
- mysql - 在行生成触发器中复制外键值
- beautifulsoup - 汤解析器无法提取类信息