Select image and text from HTML paragraph

Let’s say we have this piece:

<p><a href="http://site.com"><img src="image.jpg" rel="bla" title="bla" /></a>A purus, velit proin ut magnis habitasse et! Sociis etiam a ac, augue mattis, porttitor? Adipiscing aenean vel natoque amet ultricies placerat scelerisque augue, dignissim adipiscing turpis! Adipiscing, nascetur risus velit sed tortor magnis penatibus. A tempor aliquet dolor. Amet proin non placerat non pulvinar enim elementum urna? Pulvinar pid enim! Non odio parturient cum et pulvinar mid porta in natoque augue?</p> 

Moreover, the picture may or may not be. And if it is, then it can be both with a link and without it …

Task: if there are pictures in the text, select the first picture using the link into one variable, and the rest of the text (ignoring the rest of the pictures) into another variable.


Answer 1, authority 100%

$a = '<p><img src="image.jpg" rel="bla" title="bla" />A purus, velit proin ut magnis habitasse et! Sociis etiam a ac, augue mattis, porttitor? Adipiscing aenean vel natoque amet ultricies placerat scelerisque augue, dignissim adipiscing turpis! Adipiscing, nascetur risus velit sed tortor magnis penatibus. A tempor aliquet dolor. Amet proin non placerat non pulvinar enim elementum urna? Pulvinar pid enim! Non odio parturient cum et pulvinar mid porta in natoque augue?</p>';
$img = '';
$noimg = $a;
preg_match('/(<a[^>]+>)?(<img[^>]+>)(<\/a>)?/', $a, $m);
if($m[2]){
    $img = $m[2];
    $noimg = str_replace($m[0], '', $noimg);
}

Output two variables: $img – image tag, $noimg – text without image link


Answer 2

I’m not going to test the regular season, but something like this:

preg_match('/<img .*>/u', $siteStr, $images); //   $images