PHP Capture the image in the article to get replaced to local

Source: Internet
Author: User
This article is the PHP acquisition of the article in the image acquisition replacement to the local implementation code for a detailed analysis of the introduction, the need for friends under the reference copy code code as follows:




/**


* Gets the path to replace the picture in the article


* @param string $xstr content


* @param string $keyword Create a file name for the 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 classification exists


if (!is_dir ($DIRSLSITSS)) {


@mkdir ($DIRSLSITSS, 0777);


    }





//matching picture of Src


Preg_match_all (' #<img.*?src= "([^"]*) "[^>]*> #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 picture to 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;


}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.