Home > Article > Backend Development > PHP downloads and replaces the image address in the collected content with a local address, _PHP tutorial
To obtain all the addresses in the string into an array, we use the preg_match_all function
Copy the code as follows
$str='
Results
Array
(
[0] => Array
(
[0] =>
)
[1] => Array
(
[0] => upfiles/2009/07/1246430143_1.jpg
)
)
With the above core functions, it’s easy to do the following
The code is as follows Copy the code
/**
* Get the image path in the replacement article
* @param string $xstr content
* @param string $keyword The file name of the created photo
* @param string $oriweb URL
* @ return string
*
*/
function replaceimg($xstr,$keyword, $oriweb){
//Save path
$d = date('Ymd', time());
$dirslsitss = '/var/www/weblist/uploads/'.$keyword.'/'.$ d;//Whether the category exists
if(www.111cn.net)(!is_dir($dirslsitss)) {
@mkdir($dirslsitss, 0777);
}
//Src of matching image
preg_match_all('#
foreach($match[1] as $imgurl){
$imgurl = $imgurl;
if(is_int(strpos($imgurl, 'http'))){
$arcurl = $imgurl;
} else {
$arcurl = $oriweb.$imgurl;
}
$img=file_get_contents($arcurl);
if(!empty($img)) {
//Save the image to the server
$fileimgname = time()."-".rand(1000,9999).".jpg";
$filecachs=$dirslsitss."/".$fileimgname ;
$fanhuistr = file_put_contents( $filecachs, $img );
$saveimgfile = "/uploads/$keyword"."/".$d."/".$fileimgname;
$xstr=str_replace($imgurl,$saveimgfile,$xstr);
}
}
return $xstr;
}
from:http: //www.111cn.net/phper/php-cy/48607.htm