0

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.

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

I just want to replace the http://www0.bob.com/co/02/. It can vary.

So what I am trying to do is to replace what is between src=" to /wp-content/ 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); 

2 Answers 2

4

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,

src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg"

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" />
Sign up to request clarification or add additional context in comments.

1 Comment

I am unsure I follow.
1

You can use this regex to get the content until wp-content:

src="(.*)\/wp-content

Working demo

enter image description here

Match information

MATCH 1
1.  [5-29]  `http://www.bob.com/co/02`
MATCH 2
1.  [98-113]    `http://alex.com`

1 Comment

@M42 thanks for the suggestion but saw that OP already marked the question as solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.