preg_replace syntax (img src)

2019-09-12 11:07发布

问题:

I'm trying to find a way to locate all of the images on a page and modify their source as needed. Here is what I have so far:

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 );
}

I have three problems though:

  1. I'm starting off the 'src' tag using the relative path on the server -- but there is no check to see if:
    1. The image does actually exist on the server
    2. If the image does, is the URL given relative or not
  2. My $replacement variable is wrong (I'm not sure how to output what is only in the src tag)
  3. I'd like to not have to declare the <img> tag in the replacement, because then I'd lose everything else that was surrounding it (like classes, ids, etc).

Does anyone know how to grab just the source of images and replace that in the fashion I'm describing? I've looked at Simple HTML DOM as an alternative -- but was getting horrible performance results. Any help would be greatly appreciated. Thanks!

回答1:

1) Check if the image does actually exist on the server

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";
    }
}

Another way to replace the images:

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

this code finds source chrome://branding/content/about-logo.png and replace it with new one newlogo.png

2) To check if path is relative or absolute you can use php function parse_url