I'm having problems to replace a URL inside a HTML tag with replace-regexp.

This is the original string:

<img src="http://localhost/~user/foo.bar/place/foo_bar.jpg" ... attr="..." />

This is what I want it looks like:

<img src="<?php echo foo() . '/place/foo_bar.jpg'; ?>" ... attr="..." />

The pattern that I'm using to match until now (which is matching too much):


And the replacing pattern:

<?php foo() . '\2'; ?>"

But this is what I'm getting:

<img src="<?php echo foo() . '/place/foo_bar.jpg" ... attr="...'; ?>" />

I thought the first group would match the base url, the second group would match the rest of the url until the double quote and the third group would match the double quote itself. But I think there is some misconception in my mind (and also in my regex) that the second group is matching until the last attribute within the html tag.

So, what is this misconception?


Look at this code:

 "<?php foo() . '\\2'; ?>\""
 "<img src=\"http://localhost/~user/foo.bar/place/foo_bar.jpg\" ... attr=\"...\" />")
;; => "<img src=\"<?php foo() . '/place/foo_bar.jpg'; ?>\" ... attr=\"...\" />"

The thing that you're missing is .+? instead of .+, which makes the regexp non-greedy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.