Find Images

Find All Images in a String Using Pattern Matching

Quick tip on finding images within a string. I used this for a WordPress content conversion I did. I needed to find all the images in the post content, then copy them to a new location, and update the content with the new image URL. This works great for content scraping.

If you want to find all the images in string use:

preg_match_all("/http:\/\/www.domain.com\/([\w,\d,\-,\.,\/]+\.(?:jpe?g|png|gif))/iU",$post_content,$matches);

This also works great for any type of media:

preg_match_all("/http:\/\/www.domain.com\/([\w,\d,\-,\.,\/]+\.(?:jpe?g|png|gif|avi|mov|mp3|mp4|m4v|m4a))/iU",$post_content,$matches);

Then if we want to replace any of the these URLs in the content we can use:

preg_replace_callback("/http:\/\/www.domain.com\/([\w,\d,\-,\.,\/]+\.(?:jpe?g|png|gif|avi|mov|mp3|mp4|m4v|m4a))/iU",'url_replace',$post_content);

function url_replace($matches){

//format url to your liking
//$matches contains the results from the preg_replace pattern

return $new_url;

}

Continue Reading

  • No Related Posts