dongyue9864 2014-02-19 09:54
浏览 44
已采纳

php替换字符串并读取完整字符串

i am trying to achieve this. I have alot of HTMLs that looks somethinglike this (for example).

<div>
    <img src="http://firstsite.com/path/to/img/main.jpg" style="width: 500px; height: 400px;" />
</div>

Now i try to make a php that automatically changes the path of the images to another website, but i also want to download the images and put them into same folder structure. So far i did this:

    $input = "c:/wamp/www/primo/input12";
    $output = "c:/wamp/www/primo/output12";


    $handle  = opendir($input);
    while (($file = readdir($handle)) !== false) {
        if($file != '.' && $file != '..') {

            $data = file_get_contents($input . "/" . $file);

            $data = str_replace("http://firstsite.com/", "http://secondsite.com", $data);

            file_put_contents($output . "/" . $file, $data);

        }
    }
    closedir($handle);

This changes the path but now i need to somehow get into a variable the full path http://firstsite.com/path/to/img/main.jpg in my example in order to download the image.

Is there a way to get the full path of the images while replacing http://firstsite.com/ which is just the begining of the path ?

Thank you in advance, Daniel!

  • 写回答

2条回答 默认 最新

  • duankuang7928 2014-02-19 10:02
    关注

    Get only images:

    $data = file_get_contents($input . "/" . $file);
    
    preg_match_all('/\<img.*src=\"(.+?)\"/s', $data, $matches);
    //go through the match array and download your files
    
    $data = str_replace("http://firstsite.com/", "http://secondsite.com", $data);
    file_put_contents($output . "/" . $file, $data);
    

    Get all pathes:

    $data = file_get_contents($input . "/" . $file);
    
    preg_match_all('/http\:\/\/firstsite\.com([^\s]+?)/s', $data, $matches);
    //go through the match array and download your files
    
    $data = str_replace("http://firstsite.com/", "http://secondsite.com", $data);
    file_put_contents($output . "/" . $file, $data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了