Here we use the regular expression of PHP to implement:
The code is as follows |
Copy Code |
$content = ' Here is the content of the article, insert here a picture test '; $content = Stripslashes ($content); $img _array = Array (); Match all remote pictures Preg_match_all ("/(src| SRC) =["| ' |] {0,} (http://(. *). (gif|jpg|jpeg|bmp|png)) /isu ", $content, $img _array); Matching the Not duplicate picture $img _array = Array_unique ($img _array [2]); Print_r ($img _array); |
It matches the remote picture, and we need to keep it local. Here are two points to note:
1. Picture save path (Picture storage directory)
2. Actual access to picture address
Here is the complete example: (You can save to the local server to modify the appropriate place for testing)
The code is as follows |
Copy Code |
<! DOCTYPE html> <meta charset= "UTF-8" > <title>php Save the remote picture to the local, PHP will match the picture address in the article </title> <body> <?php Save the remote picture in the article to the local Author: yanue; File Save directory path (please replace it with your own path, you can echo it) $save _path = $_server [' Document_root ']. ' swfupload/attached/'; File Save Directory URL $save _url = '/swfupload/attached/'; $save _path = Realpath ($save _path). '/'; Picture Storage Directory $imgPath = $save _path. Date ("Ymd"); $IMGURL = $save _url. Date ("Ymd"); Create a folder if (! Is_dir ($imgPath)) { @mkdir ($imgPath, 0777); } $content = ' Here is the content of the article, insert here a picture test '; $content = Stripslashes ($content); $img _array = Array (); Match all remote pictures Preg_match_all ("/(src| SRC) =["| ' |] {0,} (http://(. *). (gif|jpg|jpeg|bmp|png)) /isu ", $content, $img _array); Matching the Not duplicate picture $img _array = Array_unique ($img _array [2]); Print_r ($img _array); Unlimited time Set_time_limit (0); foreach ($img _array as $key => $value) { $value = Trim ($value); Reading remote Pictures $get _file = @file_get_contents ($value); Save to local picture name $imgname = Date ("Ymdhis"). '_' . RAND (10000, 99999). "." . SUBSTR ($value,-3, 3); The actual file address (including path and name) saved to the local $fileName = $imgPath. '/' . $imgname; The address that is actually accessed $fileurl = $imgUrl. "/" . $imgname; File Write if ($get _file) { $fp = @fopen ($fileName, "w"); @fwrite ($fp, $get _file); @fclose ($FP); } Replace the original picture address $content = Ereg_replace ($value, $fileurl, $content); } Echo $content; ?> </body> |