2012-06-14 114 views
0

我試圖通過我的內容進行掃描並更換別的圖像源標籤(更值得注意的是,dataURIs支持時) - 基於幾個問題我已經通過讀到這裏,我想preg_replace()的preg_replace圖片src

// Base64 Encodes an image 
function wpdu_base64_encode_image($imagefile) { 
    $imgtype = array('jpg', 'gif', 'png'); 
    $filename = file_exists($imagefile) ? htmlentities($imagefile) : die($imagefile.'Image file name does not exist'); 
    $filetype = pathinfo($filename, PATHINFO_EXTENSION); 
    if (in_array($filetype, $imgtype)){ 
     $imgbinary = fread(fopen($filename, "r"), filesize($filename)); 
    } else { 
     die ('Invalid image type, jpg, gif, and png is only allowed'); 
    } 
    return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary); 
} 

// Do the do 
add_filter('the_content','wpdu_image_replace'); 
function wpdu_image_replace($content) { 
    $upload_dir = wp_upload_dir(); 
    return preg_replace('/<img.*src="(.*?)".*?>/', wpdu_base64_encode_image($upload_dir['path'].'/'.\1), $content); 
} 

我遇到的問題是wpdu_base64_encode_image($upload_dir['path'].'/'.\1)它基本上輸出preg_replace結果 - 目前獲得:

Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING 

$upload_dir['path']正確輸出的路徑我的東東圖像文件夾d,但也有一些檢查我已經嘗試過,但迄今尚未能實現:

  1. 檢查圖像源是否相對,如果是,則剝離域(當前可以?與site_url()這我假設將需要的preg_replace()
  2. 來完成。如果圖像甚至不是本地服務器(再次 - 我使用的是site_url()檢查假設),跳過它

我不熟悉preg_replace()如果任何人有意見,我會很感激。謝謝!

編輯:我應該用http://simplehtmldom.sourceforge.net/代替嗎?看起來像一個相當重的錘子,但如果這是一個更可靠的方式,那麼我就是爲了它 - 任何人都使用它?

回答

0

一般情況下,解析HTML正則表達式是不是一個很好的主意,你絕對應該考慮使用其他的東西,作爲一個適當的HTML解析器。你不太需要simplehtmldom,內置DOMDocumentgetElementsByTagName將做的工作很好。

爲了讓您當前的問題,這種類型的轉換(其中你想每次更換是一個任意功能的匹配)使用preg_replace_callback完成:

$path = $upload_dir['path']; // for brevity 

return preg_replace_callback(
    '/<img.*src="(.*?)".*?>/', 
    function ($matches) use($path) { 
     return wpdu_base64_encode_image($path.'/'.$matches[1]); 
    }, 
    $content 
); 

您當前的代碼嘗試使用在完全不相關的上下文中佔位符\1,這就是爲什麼你會得到解析錯誤。