Home > Backend Development > PHP Tutorial > PHP downloads and replaces the image address in the collected content with a local address, _PHP tutorial

PHP downloads and replaces the image address in the collected content with a local address, _PHP tutorial

WBOY
Release: 2016-07-13 10:16:20
Original
1164 people have browsed it

php downloads and replaces the image address in the collected content with a local address.

To obtain all the addresses in the string into an array, we use the preg_match_all function

Copy the code as follows
$str='

';
$pattern="/<[img|IMG].*?src=['|"](.*?(?:[.gif|.jpg]) )['|"].*?[/]?>/";
preg_match_all($pattern,$str,$match);print_r($match);
?>

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('#]*>#i', $xstr, $match );

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/898821.htmlTechArticlephp downloads and replaces the image address in the collected content with a local address, and obtains all the addresses in the string into an array We use the preg_match_all function code to copy the code as follows?php $...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template