1

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

1 Answer 1

4

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.

2
  • 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 Commented Aug 5, 2012 at 9:56
  • @DarrenSweeney You're right copied that and missed it :) Thanks. Commented Aug 5, 2012 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.