解析字符串以查找特定标记的更好方法


Better way to parse string looking for specific tag

我正在查看页面源代码,基本上想获得"og:image"图像url

我正在使用以下内容,这是有效的,我认为(除了相对URL问题)涵盖了所有可能发生的事情-但这可能不是最有效的方法-我已经对代码进行了评论,以显示每行正在做什么($html是源代码):

$og_img = explode( '<meta property="og:image" content=', $html); // strip out beginning
$og_img = explode('>', $og_img[1]); // strip out end
if(substr($og_img[0], -1)=='/'){ $og_img[0] = substr($og_img[0], 0, -1); } // strip / if used /> to close the tag
$og_img[0] = str_replace("'", "", $og_img[0]); // strip ' ... ' apostrophes if used
$og_img[0] = str_replace('"', '', $og_img[0]); // strip " ... " doubke quotes if used

有没有更有效的方法?

不要自己滚动。

使用DOM。例如

$doc = new DOMDocument();
@$doc->loadHTML($html);
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
    $meta = $metas->item($i);
    if($meta->getAttribute('property') == 'og:image')
        $og_image_content = $meta->getAttribute('content');
}

或者(还没有尝试过)使用:

get_meta_tags()