Reputation: 41
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
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