2012-06-15 77 views
0

我试图找到一种方法来查找页面上的所有图像并根据需要修改其来源。以下是我迄今为止:preg_replace语法(img src)

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

我虽然有三个问题:

  1. 我要从头开始使用服务器上的相对路径的“SRC”标签 - 但没有请检查:
    1. 图像不实际的服务器
    2. 如果影像上存在,是相对URL或给出不
  2. 我的$replacement变量是错误的(我不知道如何输出什么只是在src标签)
  3. 我想不必在替代品中声明<img>标签,因为那样我会失去一切其他围绕它(如类,ID等)。

有没有人知道如何抓住图像的来源,并用我所描述的方式取代它?我已经看过Simple HTML DOM作为替代选择 - 但获得了糟糕的表现结果。任何帮助将不胜感激。谢谢!

回答

0

1)检查图像不实际的服务器

preg_match_all("!(?<=src\=\").+(?=\"(\s|\/\>))!",$html, $match, PREG_SET_ORDER); 

$files = $match; 
foreach ($files as $file) { 
    if (file_exists($file)) { 
     echo "The file $file exists"; 
     //if image exists you can replace it like: 
     $html = str_replace($file, 'NewImagePath', $html);//$file is the found image source 
    } else { 
     echo "The file $file does not exist"; 
    } 
} 

另一种方式上存在更换图片:

$html = '<img id="brandLogo" src="chrome://branding/content/about-logo.png" alt=""/>' 
    $html = preg_replace('!(?<=src\=\").+(?=\"(\s|\/\>))!', 'newlogo.png',$html); 

这个代码是找到源chrome://branding/content/about-logo.png,并与新的newlogo.png

更换

2)要检查路径是相对还是绝对,可以使用php函数parse_url

+0

如何在html中存在多个''并且想用不同的源替换它时如何做到这一点。 – Dhara

+0

in preg_replace一个替换参数可以是一个数组 – Alex