phphtmlregexwordpresshtml-parsing

PHP preg_replace() pattern to find img with certain folder


I am trying to replace broken images from the blog post- the_content() with a placeholder. Two folders from my media folder are missing and this is causing the broken images.

So following suggestion would work for me, i felt

<?php 
$content = get_the_content();
$content = preg_replace("/<img[^>]+\>/i", "placeholderim", $content);          
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content); echo $content; ?>

But I want to match the pattern with image and the image URL should contain 2017 || 2018. How to create this pattern. Any help please!


Solution

  • This finds all html image tags that has 2019 or 2020 anywhere in it.

    /(<img[^>]+(2019|2020)+[^>]+>)/ig
    

    Demo: https://regex101.com/r/0rdwd2/1

    For PHP (untested) this would be:

    $content = get_the_content();
    $content = preg_replace("/(<img[^>]+(2019|2020)+[^>]+>)/ig", "placeholderim", $content);