2012-06-14 115 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,这就是为什么你会得到解析错误。