luftikus143
luftikus143

Reputation: 1285

How to use preg_match_all to obtain all images of a post

I have an blog entry which has multiple images in it (sometimes one, sometimes two, sometimes three) and looks a bit like this:

<a href="http://xxx/" rel="attachment w133>
  <img class="yyy" title="title1" src="http://xxx/title1.jpg" alt="" width="650" height="487" />
</a>
<a href="http://xxx/" rel="attachment w134">
  <img class="yyy" title="title2" src="http://xxx/title2.jpg" alt="" width="650" height="487" />
</a>
<a href="http://xxx/" rel="attachment w135">
  <img class="yyy" title="title3" src="http://xxx/title3.jpg" alt="" width="650" height="487" />
</a>

with some text following this.

Now, I wonder how I can use preg_match_all to extract that first part. I now somewhat about PHP programming, but never used preg_match_all.

This code here does extract the last image only, which is not enough:

$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches);

It would be great if someone could give me a hint how to achieve that, if it's possible at all. Thanks so much!

Upvotes: 0

Views: 3736

Answers (2)

Alexey
Alexey

Reputation: 7247

$post_content='<a href="http://xxx/" rel="attachment w133>
  <img class="yyy" title="title1" src="http://xxx/title1.jpg" alt="" width="650" height="487" />
</a>
<a href="http://xxx/" rel="attachment w134">
  <img class="yyy" title="title2" src="http://xxx/title2.jpg" alt="" width="650" height="487" />
</a>
<a href="http://xxx/" rel="attachment w135">
  <img class="yyy" title="title3" src="http://xxx/title3.jpg" alt="" width="650" height="487" />
</a>
';

preg_match_all('/<a\s[^>]*href=([\"\']??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU', $post_content, $matches);
//print_r ($matches);//$matches - array which contains all your images
print $matches[0][0]; //first link with image
print $matches[0][1]; //second link with image
print $matches[0][2]; //third link with image

Output:

<a href="http://xxx/" rel="attachment w133&gt;
  &lt;img class=" yyy"="" title="title1" src="http://xxx/title1.jpg" alt="" width="650" height="487">
</a>
<a href="http://xxx/" rel="attachment w134">
  <img class="yyy" title="title2" src="http://xxx/title2.jpg" alt="" width="650" height="487">
</a>
<a href="http://xxx/" rel="attachment w135">
  <img class="yyy" title="title3" src="http://xxx/title3.jpg" alt="" width="650" height="487">
</a>

Upvotes: 3

Vinicius Cainelli
Vinicius Cainelli

Reputation: 847

Try:

preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"][^\/>]*>/Ui', $post_content, $matches);
print_r($matches);

Upvotes: 0

Related Questions