Regular expression to search + Replace href = "URL"

I am useless with regular expressions and could not understand myself what I understood.

I want to search + replace some text ($ content) for any url inside the href binding with the new URL (saved as the variable $ newurl).

Change this:

<a href="http://blogurl.com/files/foobar.jpg"><img alt="foobar" src="http://blogurl.com/files/2011/03/foobar_thumb.jpg" /></a>

For this:

<a href="http://newurl.com/here/"><img alt="foobar" src="http://blogurl.com/files/2011/03/foobar_thumb.jpg" /></a>

I guess using preg_replace would be better for this. Sort of:

preg_replace('Look for href="any-url"', 
'href="$newurl"',$content);

The idea is to get all the images on the WordPress main page to link to your posts, and not to full-size images (as they are by default). Usually only one url will be replaced, but I don’t think it would be painful to replace all possible matches.

Hope all this made sense and thanks in advance!

+5
2

, . , -:

$content = get_the_content();
$pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
$newurl = get_permalink();
$content = preg_replace($pattern,$newurl,$content);

echo $content;

@WiseGuyEh

+6

-

(?<=href=("|'))[^"']+(?=("|'))

lookahead lookbehind, , , , href=" href= ' , .

. , html-, , , href, !

+4

All Articles