Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top