Page 1 of 1

If there are images, display only teh first one !

Posted: Wed Jan 21, 2009 7:56 pm
by PHPeanuts
Hi guys,

I'm pretty new with PHP, and all I've learned I did it through the blogging platform WordPress. I hope I'll keep in this beyond WordPress, because it's pretty attracting to me.

By now I have the following issue : when I call for a post, I get, as usual, all of the images I attached to it. But I'd like to retrieve only the first one.

I found this code :

Code: Select all

 
<?php
            $szPostContent = $post->post_content;
            $szSearchPattern = '~<img [^\>]*\ />~';
            preg_match_all( $szSearchPattern, $szPostContent, $aPics );
            $iNumberOfPics = count($aPics[0]);
            if ( $iNumberOfPics > 0 ) {
            for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
            echo $aPics[0][$i];
            };
            };
?>
But it gets me ALL of the images (even if with it I can forget about the text, which is the good new to me).

I'm sure it's a question of syntax : how can I manage those pretty '>' and '0' and 'i++' to get just the "first" image ?
Thanks very much if you can help.

Re: If there are images, display only teh first one !

Posted: Wed Jan 21, 2009 8:04 pm
by Burrito
use the next dimension in the matched array.

If you only need the first one, you can just use preg_match() instead of preg_match_all()

Re: If there are images, display only teh first one !

Posted: Wed Jan 21, 2009 8:57 pm
by PHPeanuts
Hi Burrito, thanks for the reply. However I'm too much bloated actually : how should I get the next dimension ? Then, in PHP.net I still get easily lost.
All I got is exclude the last image if I change the line #7 from 0 to 1, or allow only the posts with one single image to be shown if in the same line I change the sign '>' to '<' and I increase the value to 2.

Please I need some code to understand what you mean :)

Re: If there are images, display only teh first one !

Posted: Wed Jan 21, 2009 9:05 pm
by Burrito

Code: Select all

 
             $szPostContent = "<img src=\"images/whatever.jpg\"><img src=\"images/blah.jpg\">";
             $szSearchPattern = '~<img [^\>]+>~';
             preg_match( $szSearchPattern, $szPostContent, $aPics );
             echo "<pre>";
             print_r($aPics);
             echo "</pre>";
 

Re: If there are images, display only teh first one !

Posted: Wed Jan 21, 2009 9:32 pm
by PHPeanuts
Thanks very much it worked

Here is my final code :

Code: Select all

 
<?php
            $szPostContent = $post->post_content;
            $szSearchPattern = '~<img [^\>]*\ />~';
            preg_match( $szSearchPattern, $szPostContent, $aPics );
            echo $aPics[0];
?>