php
  • str-replace
  • explode
  • 2012-08-30 87 views 0 likes 
    0

    我在看頁面的源代碼,基本上更好的辦法想要得到的「OG:像」圖像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 
    

    是有更有效的方法嗎?

    +0

    如果我們能有什麼$ HTML看起來像否則的preg_match('/ /',$ html)可以做trik – 2012-08-30 09:22:48

    +0

    @FoxMaSk html只是頁面源代碼 - 不會preg_match返回表達式中的whats而不是標記之間的內容? –

    +0

    你可能想要添加另一個$匹配參數,如下所示:'preg_match('/ /',$ html,$ matches) '然後在'$ matches'上使用'print_r'。 'preg_match'只是返回true或false,不管它是否匹配;你需要將匹配放入一個變量中。 ***編輯***;我應該補充一點,這種方法會失敗,出現「',''你可能最好使用HTML解析器,如http://simplehtmldom.sourceforge.net/ – h2ooooooo

    回答

    0

    不要自己滾動它。

    請使用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() 
    
    +0

    感謝您的幫助。 –

    相關問題