首页 > 解决方案 > 如果预匹配,则从双引号中提取媒体

问题描述

我正在获取一个站点的 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="', '">');

但它看起来不太可靠。我要求的东西可以帮助不同项目中的许多其他人。如果有人可以请启发这个话题

标签: phpregex

解决方案


大多数 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',
)

*作为记录,是的,我知道测试falsewithstrpos()因为 offset0false松散地评估为false,但从逻辑上讲,如果该content值以它开头,.mp4它将不是一个可用/合格的值。


推荐阅读