Hi, I'm retrieving some html-formatted content from a MySQL DB. Included in the html are some images, coded like :

<img title="" alt="" src="/someimage.jpg" align="bottom" border="0" height="96" width="96"/>

When I am viewing the formatted html, I would like to filter out these images, replacing them with something like (Screen Shot). I wanted to use str_replace to identify and remove the <img/> refs, however obviously the exact code changes, depending on the image, therefore I need wildcards so that the actual specifics don't matter. I have tried a few approaches and done some searching around but have not been able to implement this correctly. I tried things like

$FormattedBody = str_replace("<img","<b>Screen Shot :</b>",$topic_body);

However, this removes the image but all the additional img info such as size, align etc is still shown. I tried something like:

$FormattedBody = str_replace("<img title="*" alt="*" src="*" align="*" border="*" height="*" width="*"/>","<b>Screen Shot :</b>",$topic_body);

But obviously this didn't work either. Can anyone tell what the appropriate wildcard syntax should be? or at least point me in the right direction?

cheers in advance.

    I'm a bit rusty on regular expressions, but this is exactly what they are for.

    This might do it for you:

    $replacement = '<span class="bold">Screen Shot</span>';
    $pattern = '/<img .*>/';
    
    $text = preg_replace($pattern, $replacement, $text);
    

      hmm, close, however nothing is displayed after the first screen shot replacement occurs, all subsequent text fails to display. I guess the

      $pattern = '/<img .*>/';

      part is failing to recognise the end of the <img tag, so is replacing everything after it?

        This is likely because it is behaving "greedy", i.e. matching as much as possible. You can either set the U-modifier to change this, or - preferably - make the pattern more specific, like
        $pattern = '/<img [>]*>/';

          $pattern = '/<img [^>]*>/';

          Works great, thanks alot.

            Write a Reply...