[英]preg_replace image src
我試圖瀏覽我的內容並將圖像源標簽替換為其他內容(尤其是在受支持時為dataURIs)-基於我在這里已閱讀的幾個問題,我正在嘗試preg_replace()
:
// 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)
的問題是wpdu_base64_encode_image($upload_dir['path'].'/'.\\1)
,它基本上是輸出preg_replace
結果-當前正在獲取:
Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING
$upload_dir['path']
正確地輸出了我需要的圖像文件夾的路徑,但是還有一些檢查是我已經嘗試過但尚未實現的:
site_url()
,我假設它必須是preg_replace()
嗎?) site_url()
檢查),請跳過該圖像 如果有人提出建議,我對preg_replace()
並不熟悉,我真的很感激。 謝謝!
編輯:我應該改用http://simplehtmldom.sourceforge.net/嗎? 似乎是一把沉重的錘子,但是如果那是一種更可靠的方法,那么我全力以赴-以前有人用過嗎?
通常,用正則表達式解析HTML不是一個好主意,您絕對應該考慮使用其他東西,例如適當的HTML解析器。 您並不需要simplehtmldom,內置的DOMDocument
和getElementsByTagName
可以很好地完成此工作。
為了解決當前的問題,可以使用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
,這就是為什么會出現解析錯誤的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.