2012-10-17 32 views
2

我正在編輯一個插件,我使用它將meta打開圖標籤添加到標題中。它的問題在於,它只會讓我選擇對整個網站的一張圖片..這是我做了什麼:從php中的文章中獲取圖像使用php

preg_match_all('/<img .*?(?=src)src=\"([^\"]+)\"/si', $hdog_base, $image); 

if (strlen($hdog_base) <= 25) 
{ 
    if (substr($image[0], 0, 4) != 'http') 
    { 
     $image[0] = JURI::base().$image[0]; 
    } 
    $hdog_image_tmp = $image[0]; 
} 
else 
{ 
    if (substr($image[1], 0, 4) != 'http') 
    { 
     $image[1] = JURI::base().$image[1]; 
    } 
    $hdog_image_tmp = $image[1]; 
} 
$hdog_image = '<meta property="og:image" content="'.$hdog_image_tmp.'" /> 
'; 

$ hdog_base是當前網頁我在。 第一個if語句會顯示第一張圖片,這是圖標(用於前頁主頁),其他圖片會顯示第二張圖片(每張圖片上的圖片都不相同),但結果只會顯示爲這個,不管我是在主頁上還是在網站上的其他地方:

<meta property="og:image" content="http://mysite.com/Array" /> 

有什麼建議嗎?

由於提前,

更新: 我正在做的最大的錯誤是,我試圖找到圖像的URL,而不是實際的網頁。但只是鏈接。那麼,我將如何繼續獲取當前頁面的內容?而不是$ hdog_base,這不過是一個鏈接。

更新,解決了:

我用

$buffer = JResponse::getBody(); 

得到網頁中的HTML

,然後DOM爲休息

$doc = new DOMDocument(); 
@$doc->loadHTML($buffer); 

$images = $doc->getElementsByTagName('img'); 
if (strlen($hdog_base) <= 26) 
{ 
    $image = $images->item(0)->getAttribute('src'); 
} 
else 
{ 
    $image = $images->item(1)->getAttribute('src'); 
} 
if (substr($image, 0, 4) != 'http') $image = JURI::base().$image; 
$hdog_image = '<meta property="og:image" content="'.$image.'" /> 
'; 

非常感謝cpilko爲您的幫助! :)

回答

3

在正則表達式中使用具有多個子模式的preg_match_all將返回多維數組。在你的代碼中$image[n]是一個數組。如果您在php中將數組作爲字符串進行投射,則會返回文本Array

編輯:使用正則表達式來解析HTML並不理想。你最好與DOMDocument做:

$doc = new DOMDocument(); 
@$doc->loadHTML($hdog_base); 

$images = $doc->getElementsByTagName('img'); 
if (strlen($hdog_base) <= 25) { 
    $image = $images->item(0)->getAttribute('src'); 
} else { 
    $image = $images->item(1)->getAttribute('src'); 
} 
if (substr($image[0], 0, 4) != 'http') $image .= JURI::base(); 
$hdog_image = '<meta property="og:image" content="'.$hdog_image_tmp.'" /> 
'; 
+0

其結果是這樣的:<! - 陣列 ( [0] =>'\t陣列 ( ) [1] =>數組 ( ) ) - >' – indiqa

+0

你的正則表達式不匹配任何東西。您可以在像這樣的在線正則表達式測試中對此進行疑難解答:http://www.regextester.com/ – cpilko

+0

在進行更多的研究時,正則表達式是該工作的錯誤工具。你應該使用'DOMDocument'。查看SO問題的第二和第三個答案的詳細信息http://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php – cpilko