The Code

// Inline Style Images
$content    =   preg_replace_callback('/!\[(.*)\]\s?\((.*)(.png|.gif|.jpg|.jpeg)(.*)\)/',function($match){
    return str_replace('your_search_term','your_replacement',$match[0]);

// Reference Style Images
$content    =   preg_replace_callback('/\[(.*)\]:\s?(.*)(.png|.gif|.jpg|.jpeg)/',function($match){
    return str_replace('your_search_term','your_replacement',$match[0]);

Why Would You Need This?

I had to use the above code in a Laravel project where the content is entered into a frontend form in Markdown format. When saving the data in my Laravel backend app I wanted to replace the image URL with a placeholder so that the sites URL itself isn’t hardcoded into the database. When displaying the data, the placeholder is replaced with the URL of the site again. This means that if the URL ever changes (different dev environment, staging, production etc) then the images would still load providing that the files still existed in the same location on the server.

Your use case might be different but the above regex should provide you with a decent starting point to actually find the image tags (both inline and reference style) and then manipulate them however you wish.

Would love your thoughts, please comment.x