图像文件未存储在

时间:2014-03-20 00:49:50

标签: php regex foreach

地址加载了一系列图像。

Array ( [0] => http://postfiles6.naver.ne/20140318_37/nurisdent_1395133546151D77vg_JPEG/%BB%F3%BE%CF%B5%BF%C4%A1%B0%FA_%B4%A9%B8%AE%B2%DE%BC%AD%BF%EF%C4%A1%B0%FA_%283%29.JPG?type=w2 
        [1] => http://postfiles5.naver.net/20140318_228/nurisdent_1395133546620ybrcN_JPEG/%BB%F3%BE%CF%B5%BF%C4%A1%B0%FA_%B4%A9%B8%AE%B2%DE%BC%AD%BF%EF%C4%A1%B0%FA_%281%29.JPG?type=w2 
        [2] => http://static.se2.naver.com/static/full/20130612/emoticon/1_05.gif 
        [3] => http://postfiles1.naver.net/20140318_224/nurisdent_1395133546848KfeYv_JPEG/%BB%F3%BE%CF%B5%BF%C4%A1%B0%FA_%B4%A9%B8%AE%B2%DE%BC%AD%BF%EF%C4%A1%B0%FA_%282%29.JPG?type=w2 
        [4] => http://static.se2.naver.com/static/full/20130612/emoticon/1_10.gif 
     )

我试图保存如下:

http://postfiles6.naver.ne/20140318_37/nurisdent_1395133546151D77vg_JPEG/%BB%F3%BE%CF%B5%BF%C4%A1%B0%FA_%B4%A9%B8%AE%B2%DE%BC%AD%BF%EF%C4%A1%B0%FA_%283%29.JPG?type=w2
-> 1.jpg
http://postfiles5.naver.net/20140318_228/nurisdent_1395133546620ybrcN_JPEG/%BB%F3%BE%CF%B5%BF%C4%A1%B0%FA_%B4%A9%B8%AE%B2%DE%BC%AD%BF%EF%C4%A1%B0%FA_%281%29.JPG?type=w2
-> 2.jpg

我只接受正则表达式数组,以便处理文件名

$data = preg_replace_callback("/.+\/(.+)(\?.+)?$/", create_function('$matches', '$tmp = pathinfo($matches[1]); return $tmp["filename"];'), $i); 

我只保留文件名,然后尝试通过file_put_contents保存文件。

foreach($my_img as $i){
    $tUrl = $i;


    $data = preg_replace_callback("/.+\/(.+)(\?.+)?$/", create_function('$matches', '$tmp = pathinfo($matches[1]); return $tmp["filename"];'), $i);

    $rUrl = "http://blogimgs.naver.com"; //Referer 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $tUrl);
    curl_setopt($ch, CURLOPT_REFERER, $rUrl);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30) ');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $get = curl_exec($ch);

    curl_close($ch);

    foreach($data as $v)
    {
        file_put_contents('./blog_img/'.$v.'.jpg', $get);
    }
}

创建了0字节文件,但这将是。

我想知道发生了什么事,因为。

1 个答案:

答案 0 :(得分:0)

将正则表达式更改为:

/.+\/(.+?)(\?.+)?$/

您需要使用非贪婪的重复运算符,因为下一个组(查询字符串)是可选的。使用贪婪的量词,.+将继续结束,因为它不允许任何内容与可选组匹配。

但将正则表达式替换为parse_url

可能会更好
$parsed = parse_url($i[1]);
$info = pathinfo($parsed['path']);
$data = $info['filename'];