我创建了一个图像网址数组:
$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>';
}
我需要能够分别打印每个数组项目 - 我想我在某个地方混淆了一些东西,但两个小时后......仍然在同一个地方
答案 0 :(得分: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>';
}
您可以省略正则表达式中的括号,因为它已经匹配。