user3213174
user3213174

Reputation: 73

Regex: Find only image urls in a string with PHP

I have a very complex string and i want to find and replace all urls that end with .jpg, .png, or .gif with a static url. For example;

$string = "Lorem ipsum dolor sit amet, http://www.website.com/images/some.jpg; consul delicata comprehensam eos at. Mea rebum laudem deterruisset et, ex epicuri constituto his. Sea ad appareat democritum. http://www.anotherwebsite.com/images/some.png Omnis vituperata dissentiunt an duo. Sumo diceret lobortis at sed, singulis aliquando prodesset ex sit.";

$regex = ?;
$static_image_url= "http://new_image_url";

return preg_replace($regex, $static_image_url, $string);

Please note this string may be more complex than this, urls are dynamic and this is NOT HTML.

Thank you very much in advance.

Best Regards,

EDIT:

This one worked for this case;

return preg_replace('/https?:\/\/[^ ]+?(?:\.jpg|\.png|\.gif)/', $static_image_url, $string);

Upvotes: 0

Views: 4290

Answers (2)

Schleis
Schleis

Reputation: 43800

For figuring out a regex, use the online tools for testing out your string.

http://www.regextester.com.

Since in your example string all your links start with "http://" we can start our pattern with that. We know that they are going to end in the extension of the file type (jpg, png) and a whole mess of stuff in between.

http:\/\/.+?(\.jpg|\.png|\.gif)

Using .+ will match anything and appending ? makes it ungreedy. Otherwise, we will get everything from the beginning of the first link to the end of the last.

Warning This regex is based on your example string. If the links are 'www.someplace.com/someimage.jpg' it won't be matched

Upvotes: 0

Anonymous
Anonymous

Reputation: 12027

This should replace the links as long as they don't have a space in them (since links clearly can't have spaces).

$string = "Lorem ipsum dolor sit amet, http://www.website.com/images/some.jpg; consul delicata comprehensam eos at. Mea rebum laudem deterruisset et, ex epicuri constituto his. Sea ad appareat democritum. http://www.anotherwebsite.com/images/some.png Omnis vituperata dissentiunt an duo. Sumo diceret lobortis at sed, singulis aliquando prodesset ex sit.";
$static_image_url= "http://new_image_url";
return preg_replace('/https?:\/\/[^ ]+?(?:\.jpg|\.png|\.gif)/', $static_image_url, $string);

Upvotes: 1

Related Questions