adrianTNT
adrianTNT

Reputation: 4097

regex to convert plain image url to img tags

I know there are other topics but most of them have different issues. I am trying to match image urls inside plain text and convert them to tags but the regex is not working right

/(http|https):\/\/(\S*)\.(jpg|gif|png)(\?(\S*))?/i

the above should match an image with url string:

http://www.example.com/landscape.jpg?w=120

and without query string:

http://www.example.com/landscape.jpg

but it should NOT match this one, notice the X at the end:

http://www.example.com/landscape.jpgx

that is not an url of an image and my current regex matches that, how can I adjust the regext NOT to match that last URL format ?

Upvotes: 0

Views: 1198

Answers (3)

Different vision
Different vision

Reputation: 61

Try this...

$string = 'This is image inside text string http://localhost/test/something.jpg?xml=10, http://google.com/logo.png'; 
function _callback($matches){
return '<img src="'.$matches[0].'" />'
}

echo preg_replace_callback('/https?:\/\/(.*?)\.(jpg|png|gif)(\?\w+=\w+)?/i', '_callback', $string);

Upvotes: 0

StackSlave
StackSlave

Reputation: 10617

Try this:

'/^https?\:\/\/\S+\.(jpg|gif|png)(\?\S+\=\S+)?$/i'

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

You can add a lookahead at the end that checks the next character after the url (here, a whitespace character, the end of the string or a punctuation character):

~https?://\S+\.(?:jpe?g|gif|png)(?:\?\S*)?(?=\s|$|\pP)~i

Upvotes: 1

Related Questions