jnbdz jnbdz - 1 year ago 81
PHP Question

preg_replace syntax (img src) and keeping part of the URL

I am trying to do something similar to preg_replace syntax (img src) but I don't want to take away everything in the SRC attribute.


I just want to replace the
. It can vary.

So what I am trying to do is to replace what is between
in a image tag.

How can I go about this?

Here is the code I tried:

$content = preg_replace('!(?<=src\=\").+(?=\"(\s|\/\>))!', 'http://alex.com/wp-content/', $content);

Answer Source

You can use,

$str = 'src="http://www.bob.com/co/02/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg"'; 

preg_replace("/(src=\")(.*)(\/wp-content)/", "$1http://example.com$3", $str);

Which would return,


Greedy / Non-greedy

The comment about non-greedy means that instead of using (.*) you could use (.*?). The reason you would make it non-greedy is due to the fact that (.*) would match as much as it possibly can, for example if your string contained two image links:

$str = '<img src="http://www.bob.com/co/02/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" /> <img src="http://www.bob.com/co/02/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" />'; 

Then (.*)in the regex would match everything from the first "http://..." all the way until the second "/wp-content",

print_r(preg_replace("/(src=\")(.*)(\/wp-content)/", "$1http://example.com$3", $str));

This would then return <img src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" />

Using a non-greedy catch instead would yield this result,

print_r(preg_replace("/(src=\")(.*?)(\/wp-content)/", "$1http://example.com$3", $str));
<img src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" /> <img src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download