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].'&h=320&w=214&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"&h=320&w=214&zc=1" title="" alt="">
So my questions are :
- How would you do to remove those
double quotes (while I need them in
a first moment to search for a
pattern) ? - And, how would you do to
pull only the first image in the post ?
Many thanks for any input
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:
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.