<meta charset=
"UTF-8"
>
<title>php保存远程图片到本地,php正则匹配文章中的图片地址</title>
<?php
$save_path
=
$_SERVER
[
'DOCUMENT_ROOT'
] .
'swfupload/attached/'
;
$save_url
=
'/swfupload/attached/'
;
$save_path
=
realpath
(
$save_path
) .
'/'
;
$imgPath
=
$save_path
.
date
(
"Ymd"
);
$imgUrl
=
$save_url
.
date
(
"Ymd"
);
if
(!
is_dir
(
$imgPath
)) {
@
mkdir
(
$imgPath
, 0777 );
}
$content
=
'这里是文章内容,这里插入一张图片测试 <img src="/static/imghw/default1.png" data-src="XXXXXXXXXXXXXXXXXXXX" class="lazy" alt="php正则匹配文章中的远程图片地址并下载图片至本地_php技巧" >'
;
$content
=
stripslashes
(
$content
);
$img_array
=
array
();
preg_match_all (
"/(src|SRC)=["
|'| ]{0,}(http:
$img_array
=
array_unique
(
$img_array
[2] );
print_r(
$img_array
);
set_time_limit ( 0 );
foreach
(
$img_array
as
$key
=>
$value
) {
$value
= trim (
$value
);
$get_file
= @
file_get_contents
(
$value
);
$imgname
=
date
(
"YmdHis"
) .
'_'
. rand ( 10000, 99999 ) .
"."
.
substr
(
$value
, - 3, 3 );
$fileName
=
$imgPath
.
'/'
.
$imgname
;
$fileurl
=
$imgUrl
.
"/"
.
$imgname
;
if
(
$get_file
) {
$fp
= @
fopen
(
$fileName
,
"w"
);
@fwrite (
$fp
,
$get_file
);
@fclose (
$fp
);
}
$content
=
ereg_replace
(
$value
,
$fileurl
,
$content
);
}
echo
$content
;
?>