-3

I tried to find links to JPEG/PNG images. I have search for links without file extension checkm it works OK:

preg_match_all('/<a.+href=[\'"]([^\'"]+).[\'"].*><img/i', $text, $matches);

But now I am trying to add filter for PNG/JPG :( Can you help me?..

Rudomilov
  • 1
  • 1
  • 4
    Using regex to parse HTML is a [bad idea](https://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not). You can get [strange results](https://stackoverflow.com/a/1732454/2370483) – Machavity Nov 27 '17 at 18:41
  • 2
    `"I am trying to add filter"` - What specifically *have* you *tried? Was adding `(png|jpg)` somewhere in the regex part of your attempts? (Please note that not knowing the syntax and not researching it are two different things.) – mario Nov 27 '17 at 18:44
  • mario, yes, i tried to add it. But I got URLs without extensions in $matches. – Rudomilov Nov 27 '17 at 18:53

1 Answers1

0

Solved by DOMDOcument:

$dom = new DOMDocument();
@$dom->loadHTML($post->post_content);
$dom->preserveWhiteSpace = false;

$images = $dom->getElementsByTagName('img');

foreach ($images as $image) {
    if($image->parentNode->nodeName=='a') {
        print $image->parentNode->getAttribute('href');
    }
}
Rudomilov
  • 1
  • 1