php采集文章中的图片获取替换到本地(实现代码)

yipeiwu_com6年前PHP代码库
复制代码 代码如下:

/**
 * 获取替换文章中的图片路径
 * @param string $xstr 内容
 * @param string $keyword 创建照片的文件名
 * @param string $oriweb 网址
 * @return string
 *
 */
function replaceimg($xstr,$keyword, $oriweb){

    //保存路径
    $d = date('Ymd', time());
    $dirslsitss = '/var/www/weblist/uploads/'.$keyword.'/'.$d;//分类是否存在
    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 = "/uploads/$keyword"."/".$d."/".$fileimgname;

           
            $xstr=str_replace($imgurl,$saveimgfile,$xstr);
        }
    }
    return $xstr;
}

相关文章

php获取linux命令结果的实例

如果使用php命令行里想获取etho网卡的IP怎么处理呢 ? public function get_server_ip() { if (PHP_SAPI === 'cli')...

php通过分类列表产生分类树数组的方法

本文实例讲述了php通过分类列表产生分类树数组的方法。分享给大家供大家参考。具体分析如下: 这里$list 为分类列表数组,键为分类 ID,值为分类节点对象,pid 为父分类 ID ph...

PHP使用PHPExcel实现批量上传到数据库的方法

PHP使用PHPExcel实现批量上传到数据库的方法

此例子只使用execel2003的.xls文档,若使用的是其他版本,可以保存格式为“Execel 97-2003 工作簿(*.xls)”即.xls文件类型即可! 功能说明:只能上传Exc...

PHP设计模式 注册表模式

下面是基本的注册表类的代码: 复制代码 代码如下: <?php class Registry { private static $instance; private $reques...

PHP实现上传文件并存进数据库的方法

本文实例讲述了PHP实现上传文件并存进数据库的方法。分享给大家供大家参考。具体如下: show_add.php文件如下: <?php if(!isset(...