2012-08-05 76 views
1

创建图像的URL的数组:PHP阵列/ array_unique混乱

$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); 

计数显示我我有一个结果,但是,其结果是一样的东西如下:

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)) 

随后,当我尝试从URL中打印出每张图片时,我只能得到阵列中的第一张图片:

foreach ($matches2 as $image) { 

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

} 

我ne编辑要能单独打印每个数组项目 - 我想我混乱的东西的地方,但两个小时过去了......仍然在同一个地方

回答

4

preg_match_all返回每个子匹配的数组。这意味着$matches[0]是包含您的预期结果的数组。 您的代码应该是这样的:

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>'; 
} 

你可以在你的正则表达式省略了支架,因为这已经是匹配的。

+0

千恩万谢 - +1为 - 但是,回声行应为:回声“”;作为打印图像[0]只打印字母h – 2012-08-05 09:56:24

+0

@DarrenSweeney你是正确的复制,并错过了它:)谢谢。 – flec 2012-08-05 09:58:21