Search code examples
phpwordpressbuddypress

Detect image URL and wrap in IMG tags?


Trying to hack away at a Wordpress installation to add a little more user-friendliness in the comment section of a specific plugin.

Given three cases:

1

This is a sentence and image on a newline
http://imgur.com/image.gif

2

This is a sentence http://imgur.com/image.gif

3

This is a sentence and an image with IMG tags entered by user already
<img src="This is a sentence http://imgur.com/image.gif" alt="" />

When displaying these three types of comments from a user, I'd like to have PHP detect the 1st case and 1st case only - an image url on a newline (a URL that ends in common image extensions) and simply wrap it in <img> tags when displaying.

The part I'm having trouble with, given the string of the comment, how does PHP accurate detect an image link like that?

I feel like this could be accomplished with regex but I've never been terribly skilled with it? Or is it more complicated?


Solution

  • You can use this regex will will look at the start of each line ((?m)^), any amount of horizontal whitespace (\h*) (spaces or tabs), and then the HTTP protocol (https?://). After the protocol it takes any non-space characters (\S+?) (because URLs can't have spaces) until the allowed extension (jpe?g|gif|png|tiff|svg).

    (?m)^\h*(https?://?\S+?\.(?:jpe?g|gif|png|tiff|svg))
    

    Replace with:

    <img src="$1" />
    

    https://regex101.com/r/OXvsBl/3/