Home  >  Article  >  Backend Development  >  Detailed explanation of the steps to replace the article image path with PHP to the local server

Detailed explanation of the steps to replace the article image path with PHP to the local server

php中世界最好的语言
php中世界最好的语言Original
2018-05-19 10:18:051749browse

This time I bring you php replacement article PicturesDetailed explanation of the steps to path to the local server, php replacement article picture path to the local server. What are the precautions, the following is a practical case , let’s take a look.

php Replace the image path in the article and download the image to the local server

/**
 * 获取替换文章中的图片路径
 * @param string $xstr 内容
 * @param string $oriweb 网址
 * @return string
 *
 */
function replaceimg($xstr, $oriweb){
  //保存路径
  $d = date('Ymd', time());
  $saveimgfile_1 = '/uploads/allimg/'.$d;
  $dirslsitss = DEDEROOT.$saveimgfile_1;//分类是否存在
  if(!is_dir($dirslsitss)) {
    @mkdir($dirslsitss, 0777);
  }
  //匹配图片的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)) {
      //保存图片到服务器
      $fileimgname = time()."-".rand(1000,9999).".jpg";
      $filecachs=$dirslsitss."/".$fileimgname;
      $fanhuistr = file_put_contents( $filecachs, $img );
      $saveimgfile = $saveimgfile_1."/".$fileimgname;
      $xstr=str_replace($imgurl,$saveimgfile,$xstr);
    }
  }
  return $xstr;
}

I believe you have mastered the method after reading the case in this article, and more How exciting, please pay attention to other related articles on php Chinese website!

Recommended reading:

How to implement PHP to delete folders and files under a fixed path

PHP uses asterisks to replace users Partial characters of phone number and email address

The above is the detailed content of Detailed explanation of the steps to replace the article image path with PHP to the local server. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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