palmaceous
palmaceous

Reputation: 41

PHP function to conditionally replace urls in html

So, I'm trying to create a function which does the following:

Is there an elegant way of doing that? I've been struggling to create a regular expression to take care of it me, and have only met with epic fail so far.

Any help greatly appreciated.

Upvotes: 0

Views: 185

Answers (2)

ircmaxell
ircmaxell

Reputation: 165201

First off, don't use regex to parse HTML...

Here's a basic example using XPath and DomDocument:

$dom = new DomDocument();
$dom->loadHtml($html);
$xpath = new DomXpath($dom);

$query = '//img[contains(@src, "example.com")]';
$imgs = $xpath->query($query);

foreach ($imgs as $img) {
    $src = $img->getAttribute('src');
    $parts = explode('.', $src);
    $extension = strtolower(end($parts));
    if (in_array($extension, array('jpg', 'jpeg', 'gif', 'png'))) {
        $src = str_replace('example.com', 'example2.com', $src);
        $img->setAttribute('src', $src);
    }
}

$html = $dom->saveHtml(); 

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382696

The PHP Simple HTML DOM Parser should do the trick for that.

Upvotes: 1

Related Questions