Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I create an array of image URLs:

$matches = array();

preg_match_all('#(http://[^\s]*?\.jpg)#i',$html, $matches);

$matches2 = array_unique($matches); // get unique

echo "there are ".count($matches2)." items!";

print_r($matches);

The count shows me I have one result, but, the result is something like as follows:

there are 1 items!

Array ( [0] => 

Array ( 
[0] => http://testmenow.com/248472104410838590_J3o6Jq50_b.jpg 
[1] => http://testmenow.com/cirrow_1338328950.jpg 
[2] => http://testmenow.com/madi0601-87.jpg 
[3] => http://testmenow.com/swaggirll-4.jpg 
[4] => http://testmenow.com/erythie-35.jpg ))

Subsequently, when I try to print out each image from the URL I only get the first one in the array when using this:

foreach ($matches2 as $image) {

echo '<img src='.$image[0].' width=200 height=200>';

}

I need to be able to print each array item separately - I think i'm confusing something somewhere but two hours later...still at same place

share|improve this question

1 Answer

up vote 3 down vote accepted

preg_match_all returns an array for each submatch. That means that $matches[0] ist the array that contains your expected result. Your code should look like this:

preg_match_all('#http://[^\s]*?\.jpg#i',$html, $matches);
$matches2 = array_unique($matches[0]); // get unique
echo "there are ".count($matches2)." items!";

foreach ($matches2 as $image) {
    echo '<img src='.$image.' width=200 height=200>';
}

You can omit the brackets in your regex since this is already matched.

share|improve this answer
many thanks - +1 for that - however, echo line should read: echo '<img src='.$image.' width=200 height=200>'; as printing image[0] only just prints the letter h – Darren Sweeney Aug 5 '12 at 9:56
@DarrenSweeney You're right copied that and missed it :) Thanks. – flec Aug 5 '12 at 9:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.