tags:

views:

60

answers:

1

Hello guys,

I'd like to use a resizing script for my images (Timthumb). I'm trying to pull from the database the first image contained in a post, and add to it the path to the script, as well as some extra instructions :

 <?php
  $content = $post->post_content;
  preg_match_all('/src=\"https?:\/\/[\S\w]+\"/i', $content, $matches, PREG_SET_ORDER);
  foreach($matches as $e)
  echo '<img src="http://site/scripts/timthumb.php?'.$e[0].'&amp;h=320&amp;w=214&amp;zc=1" title="" alt="">';
  {
  }
 ?>

While this is echoing all I need, it adds, in the middle of the tag, some double quotes which are missing the image's path (the same double quotes I need to detect the image):

<img src="http://site/scripts/timthumb.php?src="http://site/images/image.jpg"&amp;h=320&amp;w=214&amp;zc=1" title="" alt="">

So my questions are :

  1. How would you do to remove those double quotes (while I need them in a first moment to search for a pattern) ?
  2. And, how would you do to pull only the first image in the post ?

Many thanks for any input

+2  A: 

Firstly, use parentheses to capture just the bit you need, the URL itself. Secondly, if you only need the first image, then just use preg_match, rather than preg_match_all:

$content = $post->post_content;
if (preg_match('/src=\"(https?:\/\/[\S\w]+)\"/i', $content, $match))
{
    echo '<img src="http://site/scripts/timthumb.php?'.
        urlencode($match[1]).'&h=320&w=214&zc=1" title="" alt="">';
}

Note how the URL part of the regex is marked with () - as this is first bracketed expression, it will be element 1 of $match array.

I've also urlencoded the image URL to ensure that anything in that match is correctly encoded for use in a URL.

Paul Dixon
Paul : excellent ! many thanks. I used it without the urlencode, because it was giving me '%' signs - is that my configuration ? I'm working locally with WAMP.
Peanuts
The % signs are the urlencoding! If you get them, it shows you had characters which needed to be encoded!
Paul Dixon